How to change default Web API 2 to JSON formatter?

后端 未结 7 1169
面向向阳花
面向向阳花 2020-12-13 14:40

I have a Web API project that returns some product data. It negotiates the return type correctly depending on the Accept header (JSON/XML) of the request. The problem is, if

7条回答
  •  臣服心动
    2020-12-13 15:03

    I think Web API just uses the first formatter it can find in the Formatters collection. You can change the ordering with something like

    GlobalConfiguration.Configuration.Formatters.Clear();
    GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
    GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());
    

    But it seems the JSON formatter should be the first one by default so you might want to check if you're already modifying this collection somewhere.

提交回复
热议问题