Web Api and JSON?
I'm ramping up on MVC 4's Web API and I'm a bit confused about the default formatting. I want the API data to be in JSON. However, it's returning it in XML. According to the MVC 4 getting started video at http://www.asp.net/web-api/videos/getting-started/your-first-web-api, it should be JSON by default. But when I create a new Web Api project and run the sample, I get this:
<ArrayOfstring><string>value1</string><string>value2</string></ArrayOfstring>
I've been running around in circles trying to get this in JSON but apparently there is a lot of misinformation about this. Such as:
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonNetFormatter(serializerSettings));
It should do the trick. But I gathered this depreciated as none of the examples are working. What could I do, something simple preferably, to output data in JSON format by default?
Add this to GLOBAL.ASAX to get the response to be application/json
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
So it should look like this in context:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
OR if you need to preserve XML as a media type you could instead edit App_Start/WebApiConfig.cs :
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html") );
Which makes JSON the default response for a web browser but returns text/html .
Source
I want the API data to be in JSON. However, it's returning it in XML
How are you accessing your webapi? Are you using Chrome to access your webapi service (as Nick has mentioned in the comment)? Chrome adds the Accept header application/xml to the request...
If I add "application/json" to the content type header, it should return JSON
Try setting the 'Accept' header instead.
If I create a JsonFormatter and add it in Application_Start GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonNetFormatter(serializerSettings)); It should do the trick. But I gathered this depreciated as none of the examples are working.
If the accept header of the request is application/xml, content negotiation will still pick the XmlMediaTypeFormatter and will return application/xml. One more thing, the formatter for JSON is called JsonMediaTypeFormatter, and it is already in position 0 of the Formatters collection.
如果您只想要JSON,请清除所有默认设置的格式化程序集合,然后只添加JSON文件。
链接地址: http://www.djcxy.com/p/20432.html上一篇: 使用ASP.NET Web API默认返回json
下一篇: Web Api和JSON?