WebApi返回类型设置为json的三种方法

方法一:(改配置法) 


找到Global.asax文件,在Application_Start()方法中添加一句:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

修改后:

复制代码

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 
    WebApiConfig.Register(GlobalConfiguration.Configuration); 
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
    RouteConfig.RegisterRoutes(RouteTable.Routes); 
    // 使api返回为json 
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 
} 

复制代码

这样返回的结果就都是json类型了,但有个不好的地方,如果返回的结果是String类型,如123,返回的json就会变成"123";


解决的方法是自定义返回类型(返回类型为HttpResponseMessage)

复制代码

public HttpResponseMessage PostUserName(User user) 
{ 
    String userName = user.userName; 
    HttpResponseMessage result = new HttpResponseMessage { Content = new     StringContent(userName,Encoding.GetEncoding("UTF-8"), "application/json") }; 
    return result; 
} 

复制代码

方法二:(万金油法) 

方法一中又要改配置,又要处理返回值为String类型的json,甚是麻烦,不如就不用web 
api中的的自动序列化对象,自己序列化后再返回

复制代码

public HttpResponseMessage PostUser(User user) 
{ 
    JavaScriptSerializer serializer = new JavaScriptSerializer(); 
    string str = serializer.Serialize(user); 
    HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; 
    return result; 
} 

复制代码

方法二是我比较推荐的方法,为了不在每个接口中都反复写那几句代码,所以就封装为一个方法这样使用就方便多了。

复制代码

public static HttpResponseMessage toJson(Object obj) 
{ 
    String str; 
    if (obj is String ||obj is Char) 
    { 
        str = obj.ToString(); 
    } 
    else 
    { 
        JavaScriptSerializer serializer = new JavaScriptSerializer(); 
        str = serializer.Serialize(obj); 
    } 
    HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; 
    return result; 
}   

复制代码

方法三:(最麻烦的方法) 

方法一最简单,但杀伤力太大,所有的返回的xml格式都会被毙掉,那么方法三就可以只让api接口中毙掉xml,返回json 

先写一个处理返回的类:

复制代码

public class JsonContentNegotiator : IContentNegotiator 
{ 
    private readonly JsonMediaTypeFormatter _jsonFormatter; 

    public JsonContentNegotiator(JsonMediaTypeFormatter formatter) 
    { 
        _jsonFormatter = formatter; 
    } 

    public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) 
    { 
        var result = new ContentNegotiationResult(_jsonFormatter, new  MediaTypeHeaderValue("application/json")); 
        return result; 
    } 
} 
    

复制代码

找到App_Start中的WebApiConfig.cs文件,打开找到Register(HttpConfiguration config)方法 

添加以下代码:

var jsonFormatter = new JsonMediaTypeFormatter(); 
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); 

添加后代码如下:

复制代码

public static void Register(HttpConfiguration config) 
{ 
    config.Routes.MapHttpRoute( 
        name: "DefaultApi", 
        routeTemplate: "api/{controller}/{action}/{id}", 
        defaults: new { id = RouteParameter.Optional } 
    ); 
    var jsonFormatter = new JsonMediaTypeFormatter(); 
    config.Services.Replace(typeof(IContentNegotiator), new  JsonContentNegotiator(jsonFormatter)); 
} 
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
一、源码特点       1、先进的 HTTP 编程模型: 使用新的强类型的 HTTP 对象模型直接操作 HTTP 请求和响应, 在 HTTP客户端使用相同的编程模型和 HTTP 管道;       2、支持路由: Web API 完整支持 ASP.NET 路由, 包括路由参数和约束。 此外, 到动作的映射支持约定, 从此将不再需要向类或者方法添加类似于 [HttpPost] 之类的属性;       3、内容协商: 客户端与服务端可以一起决定 API 返回数据格式默认支持 XML, JSON 以及 Form URL-Encoded 格式, 可以扩展添加自定义格式, 甚至可以替换掉默认的内容协商策略;       4、模型绑定与验证: 模型绑定器可以轻易地从 HTTP 请求提取数据转换成在动作方法使用的 .Net 对象;       5、过滤: Web API 支持过滤, 包括总所周知的 [Authorize] 过滤标记, 可以为 Action 添加并插入自定义过滤, 实现认证、异常处理等;       6、查询聚合: 只要简单的返回 Iqueryable , Web API 将会支持通过 OData 地址约定进行查询;       7、改进的 Http 细节可测试性: Web API 不是将 HTTP 细节设置到一个静态的 Context 对象上, 而是使用 HttpRequestMessage 和 HttpResponseMessage 实例, 可以使用这些对象的泛型版本为这些 Http 类型添加自定义类型;       8、改进的依赖反转 (IoC) 支持: Web API 使用 MVC Dependency Resolver 实现的服务定位器模式在不同的场景下来获取实例;       9、基于代码的配置: Web API 单独使用代码完成配置, 从而保证了配置文件的整洁;       10、自托管 (Self-Host) : Web API 除了可以托管在 IIS , 还可以托管在进程,依旧可以使用路由以及其它的特性。 二、注意事项       1、开发环境为Visual Studio 2012,数据库为SqlServer2008,使用.net 4.0开发。
可以通过自定义一个间件来实现 ASP.NET Core WebApi 返回统一格式参数的需求,下面是一个简单的实现方式: 1. 首先创建一个类来表示统一的返回格式,如下所示: ``` public class ApiResponse<T> { public int Code { get; set; } public string Message { get; set; } public T Data { get; set; } } ``` 其,Code 表示返回码,Message 表示返回信息,Data 表示返回数据。 2. 创建一个间件来处理返回结果,如下所示: ``` public class ApiResponseMiddleware { private readonly RequestDelegate _next; public ApiResponseMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { // 执行后续间件 await _next(context); // 如果返回的是 JsonResult 类型,则对返回结果进行处理 if (context.Response.ContentType == "application/json") { var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { context.Response.Body = responseBody; var jsonSerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; // 读取原始返回结果 var streamReader = new StreamReader(context.Response.Body); var responseBodyText = await streamReader.ReadToEndAsync(); context.Response.Body.Seek(0, SeekOrigin.Begin); // 将原始返回结果反序列化为 ApiResponse 类型 var result = JsonConvert.DeserializeObject<ApiResponse<object>>(responseBodyText, jsonSerializerSettings); // 将 Null 替换为空字符串 result.Data = result.Data ?? string.Empty; // 将 ApiResponse 类型序列化为 Json 字符串 var newResponseBody = JsonConvert.SerializeObject(result); // 将处理后的结果写入 Response using (var sw = new StreamWriter(context.Response.Body)) { sw.Write(newResponseBody); } } } } } ``` 3. 在 Startup.cs 文件的 Configure 方法添加间件,如下所示: ``` public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 省略其他代码... app.UseMiddleware<ApiResponseMiddleware>(); // 省略其他代码... } ``` 这样就可以实现 ASP.NET Core WebApi 返回统一格式参数的需求,并且将返回结果的 Null 替换为空字符串。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值