I\'ve written two ASP.NET Web API applications this week which both contain a single simple controller; I\'ve tweaked each to get them to work, include exceptions, and so on
It is defined by what the calling client (eg the browser or your .NET client) passes in the Accept header:
Accept: application/json, application/xml, text/json, text/xml
Will have a preference for JSON (if possible)
So your client that returns XML needs to set the Accept
header to be the above or simply
Accept: application/json
should do the trick
Two well written answers. I will explain the default behavior in this answer.
What will be the default behavior ? i.e if "Accept: */*"
From official docs. (go through this doc completely to understand end to end)
If there are still no matches, the content negotiator simply picks the first formatter that can serialize the type.
To summarize, following is the order.
Application looks for the Accept
header. If accept header value contains specific format, it will use that formatter.
if */*
is given for Accept
header, then the first item in config.Formatters
list will be choosen.
Bonus point: If you have not edited config.Formatters
, then default will be json value.
To restrict output to only one formatter, try the instructions here:
http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#removing_the_json_or_xml_formatter
On a related note, the following link covers how ASP.NET Web API decides what output format to use depending on the HTTP request sent to it, i.e. how it chooses JSON over XML:
http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation
It may be useful if you want to still support both formats, but need to ensure your own client code always receives JSON back.