C# 如何强制 ASP.NET Web API 根据我的输入返回 JSON 或 XML 数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19975811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force ASP.NET Web API to return JSON or XML data based on my input?
提问by Rajasekar Gunasekaran
I try to get the output XML or JSON data based on my input. I used the below WEB API code but not able to exact output.
我尝试根据我的输入获取输出 XML 或 JSON 数据。我使用了下面的 WEB API 代码,但无法准确输出。
public string Get(int id)
{
if (GlobalConfiguration.Configuration.Formatters.XmlFormatter == null)
{
GlobalConfiguration.Configuration.Formatters.Add(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
if (GlobalConfiguration.Configuration.Formatters.JsonFormatter == null)
{
GlobalConfiguration.Configuration.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
}
if (id == 1)
{
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
}
else
{
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;
}
return "value";
}
采纳答案by vijayjan15
Add the below code app_start
event in global.asax
file. In API Url add the query string:
app_start
在global.asax
文件中添加以下代码事件。在 API Url 中添加查询字符串:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
e.g.:
例如:
for xml : http://localhost:49533/api/?type=xml
for json: http://localhost:49533/api/?type=json
回答by Badri
What you are trying to do will not work in a multi-threaded environment. You cannot add to and remove from the formatters collection on a per-request basis. Here is a better way of accomplishing what you want.
您尝试执行的操作在多线程环境中不起作用。您不能基于每个请求在格式化程序集合中添加和删除。这是实现您想要的更好的方法。
public HttpResponseMessage Get(int id)
{
Foo foo = new Foo();
var content = new ObjectContent<Foo>(foo,
((id == 1) ? Configuration.Formatters.XmlFormatter :
Configuration.Formatters.JsonFormatter));
return new HttpResponseMessage()
{
Content = content
};
}
回答by Jim Yarbro
If your request specifies the mime type, for example application/json
, then web api will format the response appropriately.
如果您的请求指定了 mime 类型,例如application/json
,则 web api 将适当地格式化响应。
If you are attempting to debug your web api manually, use a tool like Fiddler 2to specify the type.
如果您尝试手动调试 Web api,请使用Fiddler 2之类的工具来指定类型。
This articledescribes the concept.
这篇文章描述了这个概念。
回答by Paradox
QueryStringMapping` is nice solution but I need a default value for type.
QueryStringMapping` 是一个不错的解决方案,但我需要一个类型的默认值。
for xml : localhost:49533/api/?type=xml
对于 xml : localhost:49533/api/?type=xml
for json: localhost:49533/api/
对于 json: localhost:49533/api/
I solve that situation like that:
我是这样解决这种情况的:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
var jSettings = new JsonSerializerSettings();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings;
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", new MediaTypeHeaderValue("application/xml")));
回答by Kirkaiya
While the accepted answer by vijayjan15seems the best way to go for your specific situation (that is, using the MediaTypeMappings), you could alternatively have two different methods, one that returns XML and one that returns JSON. To do that, you can instantiate a controller-specific HttpConfiguration (to avoid modifying the one in GlobalConfiguration.Configuration):
虽然vijayjan15接受的答案似乎是针对您的特定情况(即使用 MediaTypeMappings)的最佳方法,但您也可以使用两种不同的方法,一种返回 XML,另一种返回 JSON。为此,您可以实例化特定于控制器的 HttpConfiguration(以避免修改 GlobalConfiguration.Configuration 中的那个):
public MyReturnType GetMyTypeAsXml() {
Configuration = new HttpConfiguration();
Configuration.Formatters.Clear();
Configuration.Formatters.Add(new XmlMediaTypeFormatter());
return new MyReturnType();
}
public MyReturnType GetMyTypeAsJson() {
Configuration = new HttpConfiguration();
Configuration.Formatters.Clear();
Configuration.Formatters.Add(new JsonMediaTypeFormatter());
return new MyReturnType();
}
I'm not sure how much overhead there is in spinning up a new instance of HttpConfiguration (I suspect not a lot), but the new instance comes with the Formatters collection filled by default, which is why you have to clear it right after instantiating it. Note that it if you don'tuse Configuration = new HttpConfiguration(), and instead modify Configuration directly, it modifies the GlobalConfiguration.Configuration property (so, it would impact all your other WebApi methods - bad!).
我不确定启动 HttpConfiguration 的新实例有多少开销(我怀疑不是很多),但是新实例带有默认填充的 Formatters 集合,这就是为什么您必须在实例化后立即清除它它。请注意,如果您不使用 Configuration = new HttpConfiguration(),而是直接修改 Configuration,它会修改 GlobalConfiguration.Configuration 属性(因此,它会影响您所有其他 WebApi 方法 - 不好!)。
回答by jamiebarrow
Looked into this a bit more, and found your answer in another post:
仔细研究了一下,并在另一篇文章中找到了你的答案:
public HttpResponseMessage Get(int id)
{
string content = "value";
if (id == 1)
{
return Request.CreateResponse<string>(HttpStatusCode.OK, content, Configuration.Formatters.JsonFormatter);
}
return Request.CreateResponse<string>(HttpStatusCode.OK, content, Configuration.Formatters.XmlFormatter);
}
回答by Eric Herlitz
It also works to force the accept headers. Great option if you aren't always returning HttpResponseMessage's
. I.e
它还可以强制接受标头。如果您不总是回来,这是一个不错的选择HttpResponseMessage's
。IE
Request.Headers.Add("Accept", "text/json");
return Request.CreateResponse(HttpStatusCode.OK, yourobject);
or
或者
Request.Headers.Add("Accept", "application/xml");
return new Rss20FeedFormatter(feed);