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

23

我有一个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

这是我当前的代码:

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")));
7个回答

28
在你的 App_Start/WebApiConfig.cs 中添加以下内容:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

1
在使用 Owin 时,您需要使用 WebApiConfig.Register() 中创建的 new Httpconfiguration() 中的 config 对象,而不是 GlobalConfiguration.Configuration。更多信息请参见此处 - Alastair
这里是一个链接,指向我的回答(https://dev59.com/M18e5IYBdhLWcg3w6d8_#42005182)。我包含了这个链接是因为我曾经为了让它工作而抓狂,希望能够帮助其他人避免同样的痛苦。 - Alastair
@Alastair,感谢您的贡献 :)。还有给别人点踩的人,请在踩人之前留下评论。 - Triet Doan

16

我认为Web API只是使用Formatters集合中可以找到的第一个格式化程序。您可以通过类似以下方式更改顺序

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

但看起来 JSON 格式化应该默认为第一个,因此您可能希望检查是否已在某处修改了此集合。


8
我认为您应该按照以下方式进行更改。 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")));

5

或者只需移除XmlFormatter。

var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);

1
这些字符串必须按照官方文档http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_media_type_formatter中的说明添加到Global.asax中的Application_Start()函数中。 - Deepscorn

4

以上答案均不适用于我。问题在于我从GlobalConfiguration获取格式化程序,而不是使用new HttpConfiguration()创建的config对象。以下是适用于我的代码:

public class WebApiConfig
{
    public static HttpConfiguration Register()
    {

        var config = new HttpConfiguration();
        // This next line could stay if you want xml formatting
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        // This next commented out line was causing the problem
        //var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

        // This next line was the solution
        var jsonFormatter = config.Formatters.JsonFormatter;
        jsonFormatter.UseDataContractJsonSerializer = false; // defaults to false, but no harm done
        jsonFormatter.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
        jsonFormatter.SerializerSettings.Formatting = Formatting.None;
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();           

        // remaining irrelevant code commented out
        return config;
    }
}

1
请注意拦截 text/html 媒体类型可能会导致服务器的 404 响应格式化。在我的情况下,这可能会导致潜在的安全问题,因为:
  • 恶意用户浏览到 http://api.mysite.com/one/two?test=%3Cscript%3Ealert(%27hi%27)%3C/script%3E
  • Web API 返回 404 对象,其中包含 URL。由于上面的属性,它以 JSON 格式呈现。
  • 浏览器认为返回的对象实际上是 text/html,因此它只会呈现 JSON 对象。
  • 这会导致嵌入在 URL 中的脚本标记执行。在我的示例 URL 中,它只是一个警报,但它也可能是一个 window.location 或任何邪恶的东西。

0
config.EnableSystemDiagnosticsTracing();

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

// Adding formatter for Json   
config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));

// Adding formatter for XML   
config.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接