C # Two Methods for setting the web api return type to json

Source: Internet
Author: User

When you write an api to a web api, the default response is to serialize your object and return it in XML format. How can we make it return as json? The following describes two methods:
Method 1: (Change configuration method)

Find the Global. asax file and add the following statement to the Application_Start () method:
Copy codeThe Code is as follows:
GlobalConfiguration. Configuration. Formatters. XmlFormatter. SupportedMediaTypes. Clear ();

After modification:
Copy codeThe Code is as follows:
Protected void Application_Start ()
{
AreaRegistration. RegisterAllAreas ();
WebApiConfig. Register (GlobalConfiguration. Configuration );
FilterConfig. RegisterGlobalFilters (GlobalFilters. Filters );
RouteConfig. RegisterRoutes (RouteTable. Routes );
// Return the api as json
GlobalConfiguration. Configuration. Formatters. XmlFormatter. SupportedMediaTypes. Clear ();
}

In this way, all the returned results are of the json type, but there is a bad point. If the returned result is of the String type, for example, 123, the returned json will be changed to "123 ";

The solution is to customize the return type (the return type is HttpResponseMessage)
Copy codeThe Code is as follows:
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: (Wanjin oil method)

In method 1, you have to modify the configuration and process the json with the returned value of the String type. It is very troublesome. You do not need to use the automatic serialization object in web api and then return the result after serialization.
Copy codeThe Code is as follows:
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 the recommended method. In order not to repeatedly write the code in each interface, it is much easier to encapsulate it as a method.
Copy codeThe Code is as follows:
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 3: (the most troublesome method)

Method 1 is the simplest, but it is too lethal. All returned xml formats will be truncated. Method 3 can only let the api interface drop xml and return json

First, write a class to process the returned data:
Copy codeThe Code is as follows:
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 and open the Register (HttpConfiguration config) method.

Add the following code:
Copy codeThe Code is as follows:
Var jsonFormatter = new JsonMediaTypeFormatter ();
Config. Services. Replace (typeof (IContentNegotiator), new JsonContentNegotiator (jsonFormatter ));

The added code is as follows:
Copy codeThe 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 ));
}

Method 3 if the returned result is of the String type, for example, 123, the returned json will be "123". The solution is the same as method 1.

In fact, the web api will automatically convert the returned objects to both xml and json formats. method 1 and method 3 eliminate xml responses, and method 2 customize responses.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.