WEBAPI return JSON

Source: Internet
Author: User

When the Web API writes API interface, the default return is to serialize your object and return it as XML, so how do you get it back as JSON, and here are two ways to do it:
Method One: (Change the Configuration method)


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

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

Or

GLOBALCONFIGURATION.CONFIGURATION.FORMATTERS.JSONFORMATTER.SUPPORTEDMEDIATYPES.ADD (new System.Net.Http.Headers.MediaTypeHeaderValue ("text/html"));

After modification:

protected void Application_Start () {     arearegistration.registerallareas ();     Webapiconfig.register (globalconfiguration.configuration);     Filterconfig.registerglobalfilters (globalfilters.filters);     Routeconfig.registerroutes (routetable.routes);     
GLOBALCONFIGURATION.CONFIGURATION.FORMATTERS.JSONFORMATTER.SUPPORTEDMEDIATYPES.ADD (New System.Net.Http.Headers.MediaTypeHeaderValue ("text/html"));
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear (); }

This returns the result is JSON type, but there is a bad place, if the result returned is a string type, such as 123, the returned JSON will become "123";


The workaround is to customize the return type (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 ")};     

Method Two: (Balm method)

Method one in the configuration, but also to deal with the return value of the JSON string type, is very troublesome, rather than the web
An automatic serialization object in the API, which is serialized and then returned

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"), "a Pplication/json ")};     

Method Two is my recommended method, in order not to repeat the code in each interface, so the encapsulation of a method so that the use of more convenient.

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"), "a Pplication/json ")};     return result; }   

Method Three: (the most troublesome method)

Method One is the simplest, but the lethality is too large, all the returned XML format will be killed, then the method three can only let the API interface to kill the XML, return JSON

First write a class that handles the return:

public class Jsoncontentnegotiator:icontentnegotiator {     private readonly jsonmediatypeformatter _jsonformatter;< C1/>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;     } }     

Locate the WebApiConfig.cs file in App_start, open the Find register (httpconfiguration config) method

Add the following code:

Add the following code 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  

Method Three if the returned result is a string type, such as 123, the returned JSON becomes "123", and the workaround is the same as method one.

In fact, WEBAPI will automatically convert the returned object to XML and JSON two format coexistence, method One and method three is to kill the return of the XML, and method Two is a custom return.

WEBAPI return JSON

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.