The C # Web API return type is set to JSON in two ways

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

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>//the API back to JsonGlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();} <br>

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 ")};   return result;   }

Method Two: (Balm method)

Instead of using the automatic serialization object in the Web API, it is cumbersome to change the configuration in method one and to process JSON with a return value of string, and then return it after serializing itself.

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 ")};   return result;   }

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

var jsonformatter = new Jsonmediatypeformatter ();   Config. Services.replace (typeof (Icontentnegotiator), New Jsoncontentnegotiator (Jsonformatter));

Add the following code 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 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, the Web API will automatically convert the returned object to XML and JSON two format coexistence form, method one and method three is to kill the return of the XML, and method two is the custom return.

The above is the content of the two methods of the C # Web API return type set to JSON, please follow topic.alibabacloud.com (www.php.cn) for more information!

  • 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.