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


当前回答

不要使用浏览器来测试API。

相反,尝试使用允许您指定请求的HTTP客户机,例如CURL,甚至Fiddler。

这个问题的问题在客户端,而不是API。web API根据浏览器的请求正确地工作。

其他回答

你只需要像这样修改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}"
       );
    }
config.Formatters.Remove(config.Formatters.XmlFormatter);

MVC4快速提示#3 -从ASP中删除XML格式化器。Net Web API

在全球。Asax加一行:

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

像这样:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    BundleTable.Bundles.RegisterTemplateBundles();
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}

使用RequestHeaderMapping工作得更好,因为它还在响应头中设置Content-Type = application/json,这允许Firefox(带有JSONView插件)将响应格式化为json。

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
.Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept", 
                              "text/html",
                              StringComparison.InvariantCultureIgnoreCase,
                              true, 
                              "application/json"));

不要使用浏览器来测试API。

相反,尝试使用允许您指定请求的HTTP客户机,例如CURL,甚至Fiddler。

这个问题的问题在客户端,而不是API。web API根据浏览器的请求正确地工作。