我尝试根据输入获取输出的XML或JSON数据。我使用了下面的WEB API代码,但无法精确输出。如何强制ASP.NET Web API根据我的输入返回JSON或XML数据?
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";
}
这里有个小技巧,如果你需要使用路由,而不是查询字符串,我通过继承创建一个自定义映射器从“MediaTypeMapping”并覆盖“TryMatchMediaType” –
它不适用于路由'http:// localhost:49533/api/entity/1?type = xml ' – Marusyk
它是否适用于HTTP路由,例如'[Route(“api/{type}/entity“)]'? – Lucas