使用更新的ASP。NET Web API,在Chrome中我看到XML -我如何将其更改为请求JSON,以便我可以在浏览器中查看它?我相信这只是请求头的一部分,我是正确的吗?


当前回答

如果你在WebApiConfig中这样做,默认情况下你会得到JSON,但是如果你传递text/ XML作为请求Accept头,它仍然允许你返回XML。

注意:这删除了对application/xml的支持

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}

如果你不使用MVC项目类型,因此没有这个类开始,请参阅这个答案关于如何合并它的详细信息。

其他回答

看看WebAPI中的内容协商。这些(第1部分和第2部分)非常详细和彻底的博客文章解释了它是如何工作的。

简而言之,您是对的,只需要设置Accept或Content-Type请求头。如果你的Action没有返回特定的格式,你可以设置Accept: application/json。

注意:阅读这个答案的注释,如果你使用WebAPI的默认错误处理,它可能会产生一个XSS漏洞

我只是在我的MVC Web API项目的App_Start / WebApiConfig.cs类中添加了以下内容。

config.Formatters.JsonFormatter.SupportedMediaTypes
    .Add(new MediaTypeHeaderValue("text/html") );

这确保您在大多数查询中得到JSON,但当您发送text/ XML时可以得到XML。

如果你需要将响应Content-Type设置为application/json,请检查Todd下面的回答。

命名空间正在使用System.Net.Http.Headers。

WebApiConfig是你可以配置你想要输出json还是xml的地方。缺省情况下为xml格式。在register函数中,我们可以使用HttpConfiguration Formatters来格式化输出。

System.Net.Http.Headers => MediaTypeHeaderValue("text/html")需要获得json格式的输出。

在最新版本的ASP.net WebApi 2中,在WebApiConfig.cs下,这将工作:

config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
config.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);

你只需要像这样修改App_Start/WebApiConfig.cs:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();
        //Below formatter is used for returning the Json result.
        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        //Default route
        config.Routes.MapHttpRoute(
           name: "ApiControllerOnly",
           routeTemplate: "api/{controller}"
       );
    }