如何根据我的输入强制ASP.NET Web API返回JSON或XML数据? [英] How to force ASP.NET Web API to return JSON or XML data based on my input?
本文介绍了如何根据我的输入强制ASP.NET Web API返回JSON或XML数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试根据我的输入获取输出XML或JSON数据.我使用了以下WEB API代码,但无法准确输出.
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.
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";
}
推荐答案
在global.asax
文件中添加以下代码app_start
事件.在API网址中添加查询字符串:
Add the below code app_start
event in global.asax
file. In API Url add the query string:
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")));
例如:
for xml : http://localhost:49533/api/?type=xml
for json: http://localhost:49533/api/?type=json
这篇关于如何根据我的输入强制ASP.NET Web API返回JSON或XML数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文