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


当前回答

在全球。我正在使用下面的代码。我获取JSON的URI是http://www.digantakumar.com/api/values?json=true

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

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new  QueryStringMapping("json", "true", "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。

我发现Chrome应用“高级REST客户端”非常适合使用REST服务。你可以将Content-Type设置为application/json。 高级REST客户端

从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();
    }

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

一个快速的选择是使用MediaTypeMapping专门化。下面是一个在Application_Start事件中使用QueryStringMapping的例子:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("a", "b", "application/json"));

现在,只要url包含querystring(在这种情况下,a=b), Json响应就会显示在浏览器中。

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

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

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