根据请求从MVC web api返回xml或json
鉴于以下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 GetAllProducts() { return _products; } }
使用URL http://localhost/api/Products
我获得了XML格式的产品列表。
我想做的是根据请求选择返回json或xml。 所以对于json来说,它会是;
http://localhost/api/Products.json
对于XML,它将是;
http://localhost/api/Products.xml
同样;
http://localhost/api/Products.json/1/ http://localhost/api/Products.xml/1/
这是可能的,我将如何实现此function?
另一种选择是:
http://localhost/api/json/Products/
是的,您可以使用AddUriPathExtensionMapping
实现这一AddUriPathExtensionMapping
你可以创建这样的路线:
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 } );
然后你需要扩展格式化程序:
config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json"); config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");
确保添加对System.Net.Http.Formatting
引用,因为这些方法是扩展方法,并且intellisense默认情况下不会看到它们。
请记住,在此示例中,您仍然必须使用适当的内容类型发出请求。 但是,如果您希望通过浏览器地址栏直接使用这些,您可以映射到“text / html”。
我写了一篇关于前所未有的博客文章 – 这应该是有帮助的,并带你进入更多细节http://www.strathweb.com/2012/04/different-mediatypeformatters-for-same-mediaheadervalue-in-asp-净网页API /