Given the following webapiconfig;
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
and this controller;
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;
}
}
Using the URL http://localhost/api/Products
I get a list of products in XML format.
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
and for XML, it would be;
http://localhost/api/Products.xml
likewise;
http://localhost/api/Products.json/1/
http://localhost/api/Products.xml/1/
Is this possible and how would I achieve this functionality?
An alternative would be something like;
http://localhost/api/json/Products/
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…