如何更改默认的Web API 2至JSON格式? [英] How to change default Web API 2 to JSON formatter?

查看:194
本文介绍了如何更改默认的Web API 2至JSON格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回一些产品数据的Web API项目。它正确地协商根据请求的Accept头(JSON / XML)的返回类型。问题是,如果没有指定Accept头返回XML,但我想它在默认情况下返回JSON

  http://website.com/MyPage?type=json //返回JSON
http://website.com/MyPage?type=xml //返回XML
http://website.com/MyPage //默认返回XML

下面是我目前的code如下:

  GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
新QueryStringMapping(型,XML,新MediaTypeHeaderValue(应用程序/ XML)));GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
新QueryStringMapping(型,JSON,新MediaTypeHeaderValue(应用/ JSON)));


解决方案

我觉得网络API只是使用第一个格式化它可以在格式化程序收集找到。你可以像

改变排序

  GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(新JsonMediaTypeFormatter());
GlobalConfiguration.Configuration.Formatters.Add(新XmlMediaTypeFormatter());

但它似乎JSON格式应该是,所以你可能要检查,如果你已经修改的地方这个集合默认的第一个。

I have a Web API project that returns some product data. It negotiates the return type correctly depending on the Accept header (JSON/XML) of the request. The problem is, if no Accept header is specified it returns XML, but I want it to return JSON by default

http://website.com/MyPage?type=json // returns json
http://website.com/MyPage?type=xml // returns xml
http://website.com/MyPage // returns xml by default

Here is my current code looks like:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));

解决方案

I think Web API just uses the first formatter it can find in the Formatters collection. You can change the ordering with something like

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());

But it seems the JSON formatter should be the first one by default so you might want to check if you're already modifying this collection somewhere.

这篇关于如何更改默认的Web API 2至JSON格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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