如何让 ASP.NET Web API 使用 Chrome 返回 JSON 而不是 XML? [英] How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

查看:35
本文介绍了如何让 ASP.NET Web API 使用 Chrome 返回 JSON 而不是 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

注意:阅读这个答案的评论,如果你使用WebAPI的默认错误处理,它会产生XSS漏洞

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

Note: Read the comments of this answer, it can produce a XSS Vulnerability if you are using the default error handing of WebAPI

I just add the following in App_Start / WebApiConfig.cs class in my MVC Web API project.

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

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

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

如果您需要响应 Content-Type 作为 application/json 请检查 托德的回答如下.

If you need to have the response Content-Type as application/json please check Todd's answer below.

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

这篇关于如何让 ASP.NET Web API 使用 Chrome 返回 JSON 而不是 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆