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

后端 未结 3 1761
既然无缘
既然无缘 2021-01-04 11:09

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

相关标签:
3条回答
  • 2021-01-04 11:23

    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

    0 讨论(0)
  • 2021-01-04 11:23

    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.

    0 讨论(0)
  • 2021-01-04 11:25

    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.

    0 讨论(0)
提交回复
热议问题