. NET based on MVC4 WEB API Output JSON format instance _ practical Tips

Source: Internet
Author: User
Tags tojson

This example describes the. NET based on the MVC4 WEB API output JSON format method, share for everyone to reference. The implementation methods are as follows:

1. Add JSON output in Global

Copy Code code as follows:
GLOBALCONFIGURATION.CONFIGURATION.FORMATTERS.JSONFORMATTER.MEDIATYPEMAPPINGS.ADD (New querystringmapping ("JSON"), "True", "Application/json"));

protected void Application_Start ()
{
Arearegistration.registerallareas ();
Add JSON parse 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

Copy Code code as follows:
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);
Delete parsing of XML returns string directly when the return value is string is not a JSON object
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();
}

3. Specify return format

The new method requires an assembly:

Copy Code code as follows:
System.Web.Extensions
public static Httpresponsemessage Tojson (Object obj)
{
String str;
if (obj is 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

Copy Code code as follows:
Public Httpresponsemessage GetString (string name)
{
return Tojson (name);
}

4, overriding the default implementation class all output will be reparse to JSON

New Jsoncontentnegotiator Class

Copy Code code 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;
}
}

Using Overrides in Webapiconfig

Copy Code code as follows:
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 with IQueryable or iqueryable<t> return types.
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 your application, comment out or delete the following line of code
For more information, see: Http://www.asp.net/web-api
Config. Enablesystemdiagnosticstracing ();
}

I hope this article will help you with the ASP.net program design.

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.