使用更新的ASP。NET Web API,在Chrome中我看到XML -我如何将其更改为请求JSON,以便我可以在浏览器中查看它?我相信这只是请求头的一部分,我是正确的吗?
当前回答
在最新版本的ASP.net WebApi 2中,在WebApiConfig.cs下,这将工作:
config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
config.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
其他回答
config.Formatters.Remove(config.Formatters.XmlFormatter);
在全球。我正在使用下面的代码。我获取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。
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中这样做,默认情况下你会得到JSON,但是如果你传递text/ XML作为请求Accept头,它仍然允许你返回XML。
注意:这删除了对application/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);
}
}
如果你不使用MVC项目类型,因此没有这个类开始,请参阅这个答案关于如何合并它的详细信息。
推荐文章
- 如何合并2 JSON对象从2个文件使用jq?
- 如何禁用谷歌翻译从HTML在Chrome
- 在VS Code中禁用“Comments are not allowed In JSON”错误
- 如何在Kotlin解析JSON ?
- JSON文件的蒙古导入
- Chrome开发工具:如何找出什么是覆盖CSS规则?
- 如何用jQuery / JavaScript解析JSON数据?
- jQuery在请求体中发布有效的json
- 将JSON显示为HTML
- 在JSON键名中哪些字符是有效的/无效的?
- 如何JSON序列化集?
- 如何检查JSON键是否存在?
- 返回内容与IHttpActionResult非ok响应
- 资源解释为样式表,但以MIME类型text/html传输(似乎与web服务器无关)
- Chrome iOS(和Safari)的远程调试