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


当前回答

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

其他回答

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

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

源。

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

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

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

您可以使用如下:

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

这是我在应用程序中使用过的最简单的方法。在Register函数中添加App_Start\WebApiConfig.cs中的以下3行代码:

var formatters = GlobalConfiguration.Configuration.Formatters;

formatters.Remove(formatters.XmlFormatter);

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

Asp.net web API将自动将返回的对象序列化为JSON,并且当application/ JSON添加到头中时,浏览器或接收器将理解您正在返回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"));
}