给定以下 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 格式的产品列表。
我想做的是可以选择根据请求返回 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/
这可能吗?我将如何实现此功能?
另一种选择是:
http://localhost/api/json/Products/