我正在加速使用MVC 4的Web API,我对默认格式有点困惑。我希望API数据是JSON。但是,它以XML格式返回。根据{{3}}的MVC 4入门视频,默认情况下它应该是JSON。但是当我创建一个新的Web Api项目并运行示例时,我得到了这个:
<ArrayOfstring><string>value1</string><string>value2</string></ArrayOfstring>
我一直在圈子里试图用JSON来解决这个问题,但显然有很多关于此事的错误信息。如:
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonNetFormatter(serializerSettings));
中它应该可以解决问题。但是我把这个折旧了,因为没有一个例子正在发挥作用。默认情况下,我能做些什么,最简单的方法是以JSON格式输出数据?
答案 0 :(得分:19)
将此添加到GLOBAL.ASAX以使响应为 application / json
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();
}
OR 如果您需要将XML保留为媒体类型,则可以编辑 App_Start / WebApiConfig.cs :
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html") );
这使得JSON成为网络浏览器的默认响应,但返回 text / html 。
答案 1 :(得分:4)
我希望API数据采用JSON格式。但是,它以XML格式返回
您是如何访问webapi的?您是否使用Chrome访问您的webapi服务(正如Nick在评论中提到的那样)? Chrome将Accept标头应用程序/ xml添加到请求...
如果我将“application / json”添加到内容类型标题中,它应该返回JSON
请尝试设置“接受”标题。
如果我创建一个JsonFormatter并将其添加到Application_Start GlobalConfiguration.Configuration.Formatters.Insert(0,new JsonNetFormatter(serializerSettings));它应该做的伎俩。但我收集了这个折旧,因为没有一个例子正在运作。
如果请求的accept标头是application / xml,内容协商仍将选择XmlMediaTypeFormatter并返回application / xml。还有一件事,JSON的格式化程序称为JsonMediaTypeFormatter,它已经位于Formatters集合的第0位。
答案 2 :(得分:0)
如果您只想要JSON,那么请清除所有默认值的格式化集合,然后再添加JSON。
答案 3 :(得分:0)
您无需删除xml支持即可获取JSON响应。对于GET请求,您应该设置Accept-header - 而不是Content-Type标头。对于其他HTTP动词,它取决于。这里完全解释了。
加成: 使用Google Chrome的Postman插件测试REST API。强烈推荐:))
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
答案 4 :(得分:0)
您也可以在GLOBAL.ASAX
中写下config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
这对我也有用。
答案 5 :(得分:0)
引用Felipe Leusin(How do I get ASP.NET Web API to return JSON instead of XML using Chrome?)
我只是在我的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的答案:https://stackoverflow.com/a/20556625/287145