如何将默认Web API 2更改为JSON格式化程序?

Nic*_*ahn 21 c# asp.net-web-api asp.net-web-api2

我有一个Web API项目,它返回一些产品数据.它根据请求的Accept标头(JSON/XML)正确协商返回类型.问题是,如果没有指定Accept标头,则返回XML,但我希望它默认返回JSON

http://website.com/MyPage?type=json // returns json
http://website.com/MyPage?type=xml // returns xml
http://website.com/MyPage // returns xml by default
Run Code Online (Sandbox Code Playgroud)

这是我目前的代码如下:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
Run Code Online (Sandbox Code Playgroud)

Tri*_*oan 23

将此添加到您的App_Start/WebApiConfig.cs:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Run Code Online (Sandbox Code Playgroud)


小智 16

我认为Web API只使用它可以在Formatters集合中找到的第一个格式化程序.您可以使用类似的方式更改排序

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());
Run Code Online (Sandbox Code Playgroud)

但似乎默认情况下JSON格式化程序应该是第一个,因此您可能需要检查是否已在某处修改此集合.


Jar*_*Yit 9

我认为你应该改变如下. Global.asax中:

/*For Indented formatting:*/       
 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

    /*Response as default json format
     * example (http://localhost:9090/WebApp/api/user/)
     */
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

    /*Response as json format depend on request type
     * http://localhost:9090/WebApp/api/user/?type=json
     */
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
    new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));

    /*Response as xml format depend on request type
     * http://localhost:9090/WebApp/api/user/?type=xml
     */
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
    new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 5

或者只是删除XmlFormatter

var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
Run Code Online (Sandbox Code Playgroud)