. Net outputs an instance in Json format based on MVC4 Web Api, mvc4json

Source: Internet
Author: User
Tags tojson

. Net outputs an instance in Json format based on MVC4 Web Api, mvc4json

This article describes how. Net outputs Json format based on MVC4 Web APIs. The specific implementation method is as follows:

1. Add json output to Global

Copy codeThe Code is as follows: GlobalConfiguration. Configuration. Formatters. JsonFormatter. MediaTypeMappings. Add (new QueryStringMapping ("json", "true", "application/json "));

Protected void Application_Start ()
{
AreaRegistration. RegisterAllAreas ();
// How to add json resolution? 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 codeThe Code is 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 xml parsing. If the returned value is string, the string is not a json object.
GlobalConfiguration. Configuration. Formatters. XmlFormatter. SupportedMediaTypes. Clear ();
}

3. Specify the return format

The Assembly is required for the new method:
Copy codeThe Code is 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 codeThe Code is as follows: public HttpResponseMessage GetString (string name)
{
Return ToJson (name );
}

4. rewrite all output of default implementation class will be parsed into json

Create a JsonContentNegotiator class
Copy codeThe Code is 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;
}
}

Use rewrite in WebApiConfig
Copy codeThe Code is 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 code line to enable query support for operations with IQueryable or IQueryable <T> return type.
// To avoid handling unexpected or malicious queries, use the verification settings on QueryableAttribute to verify incoming queries.
// For more information, visit the http://go.microsoft.com/fwlink? LinkId = 279712.
// Config. EnableQuerySupport ();

// To disable tracing in the application, comment out or delete the following code lines:
// For more information, see: http://www.asp.net/web-api
Config. EnableSystemDiagnosticsTracing ();
}

I hope this article will help you design your asp.net program.


How to pass Parameters in Mvc4 Web api Post?

Simply using the value/pair method to post the past is not enough?
Java request/api/method? Can the key = value be attached to the backend?
 
VS2012 net c # How to provide json or xml data interfaces for android? Web api and web service

Write a json serialization method to serialize your model into a json string and return it.

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.