Geben Sie die folgende Webapiconfig;Geben Sie entweder xml oder json von MVC web API basierend auf Anfrage
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
und dieser 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;
}
}
Unter der URL http://localhost/api/Products
ich eine Liste von Produkten im XML-Format.
Was ich tun möchte, ist die Option, entweder json oder XML basierend auf der Anfrage zurückzugeben. Also für json wäre es das;
http://localhost/api/Products.json
und für XML wäre es;
http://localhost/api/Products.xml
ebenfalls;
http://localhost/api/Products.json/1/
http://localhost/api/Products.xml/1/
Ist das möglich und wie würde ich diese Funktionalität erreichen?
Eine Alternative wäre etwas wie;
http://localhost/api/json/Products/
Die Routen zu funktionieren scheinen, aber die Erweiterung Zeug nicht alles tun. Ich habe diese zu global.asax hinzugefügt, ist das ein Problem? – ChrisBint
Chris, verwenden Sie {ext} anstelle von {extension}, da {ext} fest codiert zu sein scheint, um auf den zugeordneten Formatierer zu verweisen. – MCattle
Toller Thread. Wie @Mcattle sagte, immer daran denken: EXT anstelle von EXTENSION –