11

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 but they are configured almost the same as far as I can see.

One of these returns JSON and the other returns XML. I want them both to return JSON!

I've looked for some configuration which might control this behaviour but I'm having no joy. Where is the setting which controls the serialization type used by the ASP.NET Web API?

Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169

3 Answers3

11

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

wal
  • 17,409
  • 8
  • 74
  • 109
  • What if "Accept: */*"? which one will be preferred ? xml or json ? any pointer will be really helpful.. – SRIDHARAN Aug 26 '20 at 10:51
  • 1
    @SRIDHARAN that will depend on the default behavior of the server - there is no single answer. many would default to xml but that is just a guess. Any modern build API will default to JSON tho – wal Aug 26 '20 at 12:01
  • Please refer https://stackoverflow.com/a/63599337/5349104 – SRIDHARAN Aug 26 '20 at 14:03
2

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.

Dave R.
  • 7,206
  • 3
  • 30
  • 52
0

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.

  1. Application looks for the Accept header. If accept header value contains specific format, it will use that formatter.

  2. 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.

SRIDHARAN
  • 1,196
  • 1
  • 15
  • 35