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


当前回答

在WebApiConfig.cs中,在Register函数的末尾添加:

// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);

源。

其他回答

您可以使用如下:

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

使用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"));

由于问题是chrome特定的,你可以得到邮递员扩展,它允许你设置请求内容类型。

从MSDN构建一个单页应用程序与ASP。NET和AngularJS(大约41分钟)。

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // ... possible routing etc.

        // Setup to return json and camelcase it!
        var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        formatter.SerializerSettings.ContractResolver =
            new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
    }

它应该是当前的,我试过了,它工作。

config.Formatters.Remove(config.Formatters.XmlFormatter);