. 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"));
1 protected voidApplication_Start ()2 {3 Arearegistration.registerallareas ();4     //add JSON parsing using methodshttp://xxx/api/action?json=true5GLOBALCONFIGURATION.CONFIGURATION.FORMATTERS.JSONFORMATTER.MEDIATYPEMAPPINGS.ADD (NewQuerystringmapping ("JSON","true","Application/json"));6 Webapiconfig.register (globalconfiguration.configuration);7 filterconfig.registerglobalfilters (globalfilters.filters);8 routeconfig.registerroutes (routetable.routes);9 bundleconfig.registerbundles (bundletable.bundles);Ten}

2. Delete XML parsing in Global

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();
1 protected voidApplication_Start ()2 {3 Arearegistration.registerallareas ();4 Webapiconfig.register (globalconfiguration.configuration);5 filterconfig.registerglobalfilters (globalfilters.filters);6 routeconfig.registerroutes (routetable.routes);7 bundleconfig.registerbundles (bundletable.bundles);8     //remove parsing of XML when the return value is string, return string is not a JSON object directly9 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();Ten}

3. Specify return format

1 New method requires assembly: System.Web.Extensions2  Public Statichttpresponsemessage ToJson (Object obj)3 {4 String str;5     if(obj isString | | Obj isChar)6     {7str =obj. ToString ();8     }9     ElseTen     { One         varSerializer =NewJavaScriptSerializer (); Astr =Serializer. Serialize (obj); -     } -     varresult =Newhttpresponsemessage {Content =NewStringcontent (str, encoding.getencoding ("UTF-8"),"Application/json") }; the     returnresult; -}

Convert user method to JSON object output

1  Public Httpresponsemessage GetString (string  name)2{3     return ToJson (name); 4 }

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

1 New Jsoncontentnegotiator class2  Public classJsoncontentnegotiator:icontentnegotiator3 {4     Private ReadOnlyJsonmediatypeformatter _jsonformatter;5      PublicJsoncontentnegotiator (Jsonmediatypeformatter formatter)6     {7_jsonformatter =formatter;8     }9 Ten      PublicContentnegotiationresult Negotiate (type type, httprequestmessage request, ienumerable<mediatypeformatter>formatters) One     { A         varresult =NewContentnegotiationresult (_jsonformatter,NewMediatypeheadervalue ("Application/json")); -         returnresult; -     } the}
1 using overrides in Webapiconfig2  Public Static voidRegister (httpconfiguration config)3 {4 CONFIG. Routes.maphttproute (5Name"Defaultapi",6Routetemplate:"Api/{controller}/{id}",7DefaultsNew{id =Routeparameter.optional}8     );9 Ten     varJsonformatter =NewJsonmediatypeformatter (); OneConfig. Services.replace (typeof(Icontentnegotiator),NewJsoncontentnegotiator (Jsonformatter)); A  -     //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.  the     //For more information, please visithttp://go.microsoft.com/fwlink/?LinkId=279712.  -     //CONFIG. Enablequerysupport (); -  -     //to disable tracing in your application, comment out or delete 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.