在Application_Start()方法中添加一句: GlobalConfiguration.Configurati

时间:2022-04-26 08:56:03

web api写api接口时默认返回的是把你的东西序列化后以XML形式返回,那么怎样才华让其返回为json呢,下面就介绍两种要领: 
要领一:(改配置法) 


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

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

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

改削后:

protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); // 使api返回为json
   //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html")); 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.WordStr(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

添加儿女码如下: