使用更新的ASP。NET Web API,在Chrome中我看到XML -我如何将其更改为请求JSON,以便我可以在浏览器中查看它?我相信这只是请求头的一部分,我是正确的吗?
当前回答
您可以使用如下:
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
其他回答
看看WebAPI中的内容协商。这些(第1部分和第2部分)非常详细和彻底的博客文章解释了它是如何工作的。
简而言之,您是对的,只需要设置Accept或Content-Type请求头。如果你的Action没有返回特定的格式,你可以设置Accept: application/json。
这段代码使json成为我的默认格式,并允许我使用XML格式。我将附加xml=true。
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
谢谢大家!
上面的大多数答案都很有道理。 由于您看到的数据是以XML格式格式化的,这意味着应用了XML格式化器,因此您可以通过从HttpConfiguration参数中删除XMLFormatter来查看JSON格式
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.EnableSystemDiagnosticsTracing();
}
因为JSON是默认格式
在最近更新了核心库和Json之后,多年来一直使用Felipe Leusin的答案。Net,我遇到了System.MissingMethodException:SupportedMediaTypes。 在我的案例中,解决方案是安装System.Net.Http,希望对遇到同样意外异常的其他人有所帮助。NuGet显然会在某些情况下删除它。手动安装后,该问题得到了解决。
在全球。我正在使用下面的代码。我获取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"));
}
推荐文章
- 如何合并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)的远程调试