如何让 ASP.NET Web API 使用 Chrome 返回 JSON 而不是 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9847564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:14:26  来源:igfitidea点击:

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

jsongoogle-chromeasp.net-web-api

提问by naspinski

Using the newer ASP.NET Web API, in ChromeI am seeing XML - how can I change it to request JSONso I can view it in the browser? I do believe it is just part of the request headers, am I correct in that?

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

回答by Felipe Leusin

I just add the following in App_Start / WebApiConfig.csclass in my MVC Web APIproject.

我只是App_Start / WebApiConfig.cs在我的 MVC Web API项目的类中添加以下内容。

config.Formatters.JsonFormatter.SupportedMediaTypes
    .Add(new MediaTypeHeaderValue("text/html") );

That makes sure you get JSON on most queries, but you can get XMLwhen you send text/xml.

这可确保您在大多数查询中获得 JSON,但您可以XML在发送text/xml.

If you need to have the response Content-Typeas application/jsonplease check Todd's answer below.

如果您需要得到回复Content-Typeapplication/json请查看下面托德的回答

NameSpaceis using System.Net.Http.Headers.

NameSpace正在使用System.Net.Http.Headers.

回答by Glenn Slaven

If you do this in the WebApiConfigyou will get JSON by default, but it will still allow you to return XML if you pass text/xmlas the request Acceptheader

如果您在 中执行此操作,WebApiConfig默认情况下您将获得 JSON,但如果您text/xml作为请求Accept标头传递,它仍然允许您返回 XML

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}

If you are not using the MVC project type and therefore did not have this class to begin with, see this answerfor details on how to incorporate it.

如果您没有使用 MVC 项目类型,因此没有此类开始,请参阅此答案以获取有关如何合并它的详细信息。

回答by dmit77

Using RequestHeaderMapping works even better, because it also sets the Content-Type = application/jsonin the response header, which allows Firefox (with JSONView add-on) to format the response as JSON.

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

回答by Todd Menier

I like Felipe Leusin's approachbest - make sure browsers get JSON without compromising content negotiation from clients that actually want XML. The only missing piece for me was that the response headers still contained content-type: text/html. Why was that a problem? Because I use the JSON Formatter Chrome extension, which inspects content-type, and I don't get the pretty formatting I'm used to. I fixed that with a simple custom formatter that accepts text/html requests and returns application/json responses:

我最喜欢Felipe Leusin 的方法- 确保浏览器获得 JSON,而不会影响来自真正需要 XML 的客户端的内容协商。对我来说唯一缺少的部分是响应头仍然包含内容类型:text/html。为什么这是个问题?因为我使用JSON Formatter Chrome 扩展程序,它检查内容类型,而且我没有得到我习惯的漂亮格式。我用一个简单的自定义格式化程序修复了这个问题,它接受文本/html 请求并返回应用程序/json 响应:

public class BrowserJsonFormatter : JsonMediaTypeFormatter
{
    public BrowserJsonFormatter() {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        this.SerializerSettings.Formatting = Formatting.Indented;
    }

    public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) {
        base.SetDefaultContentHeaders(type, headers, mediaType);
        headers.ContentType = new MediaTypeHeaderValue("application/json");
    }
}

Register like so:

像这样注册:

config.Formatters.Add(new BrowserJsonFormatter());

回答by Yakir Manor

MVC4 Quick Tip #3–Removing the XML Formatter from ASP.Net Web API

MVC4 快速提示 #3 – 从 ASP.Net Web API 中删除 XML 格式化程序

In Global.asaxadd the line:

Global.asax添加行:

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

like so:

像这样:

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

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

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

回答by Michael Vashchinsky

In the WebApiConfig.cs, add to the end of the Registerfunction:

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

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

Source.

来源

回答by Diganta Kumar

In the Global.asaxI am using the code below. My URI to get JSON is http://www.digantakumar.com/api/values?json=true

Global.asax我使用下面的代码。我获取 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"));
}

回答by Aaron Daniels

Have a look at content negotiation in the WebAPI. These (Part 1& Part 2) wonderfully detailed and thorough blog posts explain how it works.

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

In short, you are right, and just need to set the Acceptor Content-Typerequest headers. Given your Action isn't coded to return a specific format, you can set Accept: application/json.

简而言之,您是对的,只需要设置AcceptContent-Type请求标头即可。鉴于您的 Action 未编码为返回特定格式,您可以设置Accept: application/json.

回答by Chris S

As the question is Chrome-specific, you can get the Postman extensionwhich allows you to set the request content type.

由于问题是特定于 Chrome 的,您可以获得Postman 扩展程序,它允许您设置请求内容类型。

Postman

邮差

回答by suhair

One quick option is to use the MediaTypeMapping specialization. Here is an example of using QueryStringMapping in the Application_Start event:

一种快速选择是使用 MediaTypeMapping 特化。以下是在 Application_Start 事件中使用 QueryStringMapping 的示例:

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

Now whenever the url contains the querystring ?a=b in this case, Json response will be shown in the browser.

现在每当 url 包含查询字符串 ?a=b 在这种情况下,Json 响应将显示在浏览器中。