Home > Backend Development > C#.Net Tutorial > Two methods to set C# web api return type to json

Two methods to set C# web api return type to json

高洛峰
Release: 2017-01-18 09:29:48
Original
1229 people have browsed it

When web api writes an api interface, the default return is to serialize your object and return it in XML form. So how can you make it return as json? Here are two methods:
Method 1: (Change Configuration method)

Find the Global.asax file and add a sentence in the Application_Start() method:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
Copy after login

After modification:

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(); 
}
Copy after login

The results returned in this way are all json types Yes, but there is a disadvantage. If the returned result is of String type, such as 123, the returned json will become "123";

The solution is to customize the return type (the return type is 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; 
}
Copy after login

Method 2: (Ten thousand gold oil method)

In method 1, you need to change the configuration and process the json return value of String type. It is very troublesome. It is better not to use web api. The automatic serialization object in, serialize it yourself and then return it.

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; 
}
Copy after login

Method 2 is the method I recommend more. In order not to repeatedly write those few lines of code in each interface, it is encapsulated into one method. This makes it much easier to use.

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; 
}
Copy after login

Method three: (the most troublesome method)

Method one is the simplest, but it is too lethal. All returned xml formats will be destroyed, so method three can only Let the api interface kill xml and return json

First write a class to process the return:

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; 
} 
}
Copy after login

Find the WebApiConfig.cs file in App_Start, open it and find the Register(HttpConfiguration config) method

Add the following code:

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

The added code is as follows:

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)); 
}
Copy after login

Method 3 If the returned result is String type, such as 123, the returned json will become "123" , the solution is the same as method one.

In fact, web api will automatically convert the returned object into a form in which xml and json formats coexist. Methods 1 and 3 eliminate the return of xml, while method 2 is to customize the return.

For more related articles on the two methods of setting the return type of C# web api to json, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template