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


当前回答

这里有一个类似于杰森的解决方案。ceneno 's和其他答案,但使用System.Net.Http.Formatting的内置扩展。

public static void Register(HttpConfiguration config)
{
    // add support for the 'format' query param
    // cref: http://blogs.msdn.com/b/hongyes/archive/2012/09/02/support-format-in-asp-net-web-api.aspx
    config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
    config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");

    // ... additional configuration
 }

在WebApi的早期版本中,该解决方案主要用于支持OData的$格式,但它也适用于非OData实现,并返回 内容类型:application / json;Charset =utf-8报头。

它允许您在使用浏览器测试时将&$format=json或&$format=xml附加到uri的末尾。在使用非浏览器客户端(可以设置自己的头文件)时,它不会干扰其他预期行为。

其他回答

你只需要像这样修改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}"
       );
    }

您可以使用如下:

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

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

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

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

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

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