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.