. Net MVC 4 Web Api output JSON format

Source: Internet
Author: User
Tags tojson

1. Add JSON output in Global

GLOBALCONFIGURATION.CONFIGURATION.FORMATTERS.JSONFORMATTER.MEDIATYPEMAPPINGS.ADD (New querystringmapping ("JSON", "True", "Application/json"));
protected void Application_Start () {     arearegistration.registerallareas ();     Add JSON parsing  using method Http://xxx/api/action?json=true     GLOBALCONFIGURATION.CONFIGURATION.FORMATTERS.JSONFORMATTER.MEDIATYPEMAPPINGS.ADD (New querystringmapping ("JSON", "True", "Application/json"));     Webapiconfig.register (globalconfiguration.configuration);     Filterconfig.registerglobalfilters (globalfilters.filters);     Routeconfig.registerroutes (routetable.routes);     Bundleconfig.registerbundles (Bundletable.bundles); }

2. Delete XML parsing in Global

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();
protected void Application_Start () {     arearegistration.registerallareas ();     Webapiconfig.register (globalconfiguration.configuration);     Filterconfig.registerglobalfilters (globalfilters.filters);     Routeconfig.registerroutes (routetable.routes);     Bundleconfig.registerbundles (bundletable.bundles);     Remove parsing of XML when the return value is string, return string is not a JSON object     directly GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();  }

3. Specify return format

New method requires assembly: System.Web.Extensions public static httpresponsemessage ToJson (Object obj) {     String str;     if (obj is a String | | obj is Char)     {         str = obj. ToString ();     }     else     {         var serializer = new JavaScriptSerializer ();         str = serializer. Serialize (obj);     }     var result = new Httpresponsemessage {Content = new stringcontent (str, encoding.getencoding ("UTF-8"), "Application/json" ) };     return result; }

Convert user method to JSON object output

Public Httpresponsemessage GetString (string name) {     return ToJson (name);}

4. Overriding the default implementation class all output will be re-parsed into JSON

New Jsoncontentnegotiator class 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;     } }
Webapiconfig is used in the override public static void Register (Httpconfiguration config) {     config. Routes.maphttproute (         name: "Defaultapi",         routetemplate: "Api/{controller}/{id}",         defaults:new {id = Routeparameter.optional}     );      var jsonformatter = new Jsonmediatypeformatter ();     Config. Services.replace (typeof (Icontentnegotiator), New Jsoncontentnegotiator (Jsonformatter));      Uncomment the following line of code to enable query support for operations that have a IQueryable or iqueryable<t> return type.     //To avoid handling unexpected queries or malicious queries, use the validation settings on Queryableattribute to validate incoming queries.     //For more information, please visit http://go.microsoft.com/fwlink/?LinkId=279712.     //config. Enablequerysupport ();      To disable tracing in the application, comment out or remove the following line of code     //For more information, see: Http://www.asp.net/web-api     config. Enablesystemdiagnosticstracing (); }

. Net MVC 4 Web Api output JSON format

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.