Home  >  Article  >  Backend Development  >  Two methods to set C# web api return type to json

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

黄舟
黄舟Original
2017-01-19 10:39:391219browse

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();

After modification:

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

The results returned in this way will be It is of json type, 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;   
}

Method 2: (One-size-fits-all method)

Method 1 requires changing the configuration and processing json whose return value is String type. It is very troublesome, so why not just Instead of using the automatic serialization object in the web api, 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;   
}

Method 2 is my more recommended method. In order not to repeatedly write those few lines of code in every interface, I encapsulate it. It is much more convenient to use it this way for a method.

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;   
}


Method three: (the most troublesome method)

Method one is the simplest, but it is too lethal, and all returned xml formats will be destroyed. Then method three can only kill the xml in the api interface 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;   
}   
}

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

Add the following code:

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

The code after adding is as follows:

<br>public static void Register(HttpConfiguration config) <br>{ <br>config.Routes.MapHttpRoute( 
<br>name: "DefaultApi", <br>routeTemplate: "api/{controller}/{action}/{id}", <br>defaults: new { 
id = RouteParameter.Optional } <br>);var jsonFormatter = new JsonMediaTypeFormatter();   
onfig.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));} <br>

Method 3 If the returned result is String type, such as 123, return The json will become "123", and 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.

The above is the content of the two methods of setting the C# web api return type to json. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
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