asp.net MVC 4 Web API Learn how to return JSON data correctly

Source: Internet
Author: User
Tags json


The Web API could have been returned in JSON format, why should we make some changes to it?

Because the Web API returns XML by default, the Content-type:application/json is set in the submission request;

Returns the JSON-formatted data!

But how do you get it to just return the JSON-formatted data?

Sometimes you meet this need!

That's the way I started it.
public static void Register (Httpconfiguration config)
{
Config. Routes.maphttproute (
Name: "Defaultapi",
Routetemplate: "Api/{controller}/{id}",
defaults:new {id = routeparameter.optional}
);

var json = config. Formatters.jsonformatter;
Json. serializersettings.preservereferenceshandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
Config. Formatters.remove (config. Formatters.xmlformatter);
}

Can return JSON format, but inexplicably more than a $id do not know where to come!

The final correct approach is to use a custom content negotiation that returns only JSON result instead of the default content negotiation in the Web API. Conneg extends by implementing the Negotiator method of Icontentnegotiator. The Negotiator method returns Contentnegotiationresult (it wraps the headers and formatter you choose). The following method returns the custom Conneg negotiator by passing a jsonmediatypeformatter to the Applicaton/json of Content-type and Jsonmediatypeformatter. This approach avoids the need to re-create the formatter each time a request is made.

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

Next, you need to register your new implementation mechanism on the Httpconfiguration instance:

var jsonformatter = new Jsonmediatypeformatter ();
Optional:set Serializer Settings here
Config. Services.replace (typeof (Icontentnegotiator), New Jsoncontentnegotiator (Jsonformatter));

By replacing the default defaultcontentnegotiator, we use our custom jsoncontentnegotiator, which only supports JSON and can be returned immediately.

If you want to get a deeper understanding of content negotiation, you can view the author's article.

Summarize

By using a custom jsoncontentnegotiator to replace the system default Defaultcontentnegotiator, a good implementation of the Web API returns only JSON functionality, with no additional overhead.

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.