根据请求从 MVC web api 返回 xml 或 json [英] Return either xml or json from MVC web api based on request
问题描述
给定以下 webapiconfig;
Given the following webapiconfig;
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
和这个控制器;
public class ProductsController : ApiController
{
Product[] _products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return _products;
}
}
使用 URL http://localhost/api/Products
我得到一个 XML 格式的产品列表.
Using the URL http://localhost/api/Products
I get a list of products in XML format.
我想做的是可以选择根据请求返回 json 或 xml.所以对于 json,它会是;
What I would like to do is have the option to return either json or xml based on the request. So for json, it would be;
http://localhost/api/Products.json
对于 XML,它将是;
and for XML, it would be;
http://localhost/api/Products.xml
同样;
http://localhost/api/Products.json/1/
http://localhost/api/Products.xml/1/
这可能吗?我将如何实现此功能?
Is this possible and how would I achieve this functionality?
另一种可能是;
http://localhost/api/json/Products/
推荐答案
是的,您可以使用 AddUriPathExtensionMapping
您可以像这样创建路由:
You can create routes like this:
routes.MapHttpRoute(
name: "Api UriPathExtension",
routeTemplate: "api/{controller}.{extension}/{id}",
defaults: new { id = RouteParameter.Optional, extension = RouteParameter.Optional }
);
routes.MapHttpRoute(
name: "Api UriPathExtension ID",
routeTemplate: "api/{controller}/{id}.{extension}",
defaults: new { id = RouteParameter.Optional, extension = RouteParameter.Optional }
);
然后你需要扩展格式化程序:
Then you need to extend the formatters:
config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");
确保添加对 System.Net.Http.Formatting
的引用,因为这些方法是扩展方法,默认情况下智能感知不会看到它们.
MAke sure to add reference to System.Net.Http.Formatting
, as these methods are extension methods and intellisense won't see them by default.
请记住,在此示例中,您仍然必须使用适当的内容类型发出请求.但是,如果您想通过浏览器地址栏直接访问这些内容,您可以映射到text/html".
Remember in this example, you still have to issue the request with the appropriate content-type. However, if you want to have these directly available via the browser address bar you can map to "text/html".
我不久前写了一篇关于所有这些的博客文章 - 这应该会有所帮助并带您了解更多细节http://www.strathweb.com/2012/04/different-mediatypeformatters-for-same-mediaheadervalue-in-asp-net-web-api/
I wrote a blog post about all that a while ago - which should be helpful and take you into more details http://www.strathweb.com/2012/04/different-mediatypeformatters-for-same-mediaheadervalue-in-asp-net-web-api/
这篇关于根据请求从 MVC web api 返回 xml 或 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!