Contents
Today, when I was playing a web API problem, I found that the output JSON was changed to XML.
The problem is as follows:
When IE is used, JSON is returned.
We can see that
The first time is XML, and the second time is JSON.
Later I found the rule:
The browser requests are different.
IE is JSON
Firefox is XML
Then, test it in fiddle.
The result is as follows:
If accept: Application/XML is added, XML format data is returned.
If you do not add or change it to accept: Application/JSON, JSON data is returned.
CodeRoughly as follows:
Public ClassImagewordapicontroller: apicontroller
{
PublicMiniwordimagesjson getimages (StringID)
{
..................
ReturnNewMiniwordimagesjson {id = 1 };
}
}
Later read http://stackoverflow.com/questions/9847564/how-do-i-get-mvc-4-webapi-to-return-json-instead-of-xml-using-chrome
Don't understand.
Solution
In fact, you can do this:
1. In the configuration file
Globalconfiguration. configuration. formatters. jsonformatter. mediatypemappings. Add (NewQuerystringmapping ("JSON","True","Application/JSON"));
Http://111.com/a/1? JSON = true
Http://111.com/a/1? Xml = true
To limit the returned status.
2. During the request
Add accept: Application/XML to request the return status. Figure above
Add content
If you force the output of JSON directly on the server side, you can do this directly.
Globalconfiguration. configuration. formatters. Clear (); globalconfiguration. configuration. formatters. Add (NewJsonmediatypeformatter ());
Clear the file before adding jsonmediatype
Although this scheme is cleared, adding it will cause some resource waste.
It is better to control at the source, always return the jsonmedia type
Public ClassJsoncontentnegotiator: icontentnegotiator {PublicContentnegotiationresult negotiate (type, httprequestmessage request, ienumerable> mediatypeformatter <Formatters ){VaRResult =NewContentnegotiationresult (NewJsonmediatypeformatter (),NewMediatypeheadervalue ("Application/JSON"));ReturnResult ;}}
Then register
Config. Services. Replace (Typeof(Icontentnegotiator ),NewJsoncontentnegotiator ());
References:
Http://stackoverflow.com/questions/12629144/how-to-force-asp-net-web-api-to-always-return-json/12629311#12629311