How do I specify if I want JSON or XML in ASP.NET Web API?

Viewed 6222

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?

3 Answers

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.

Related