ASP.NET API méthode de reliure Web
-
27-10-2019 - |
Question
J'ai deux méthodes comme celle-ci
public class ProductController : ApiController
{
public Product GetProductById(int id)
{
var product = ... //get product
return product;
}
public Product GetProduct(int id)
{
var product = ... //get product
return product;
}
}
Quand je url appelle: GET http: // localhost / api / produit / 1 . Je veux la première méthode est invoquée, pas la seconde méthode.
Comment puis-je faire?
La solution
You need unique URIs. You can modify your route to get this:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Now you can access your API like this:
http://localhost/api/product/GetProductById/1
http://localhost/api/product/GetProduct/1
I've written a little introduction to ASP.NET Web API which shows some of the differences to WCF Web API.
You can also add a default action, e.g. the one the lists all products so you can do something like this:
http://localhost/api/product/ // returns the list without specifying the method
and the other one is invoked this way
http://localhost/api/product/byid/1 // returns the list without specifying the method
What I do is having a ProductsController and a ProductController. ProductsController is responsible for operations on Collections of T (get all) and ProductController is responsible for operations on T (like getting a specific one).