ASP.NET Web API binding method
-
27-10-2019 - |
题
I have two methods like this
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;
}
}
When I call url: GET http://localhost/api/product/1 . I want the first method is invoked, not the second method.
How can I do that ?
解决方案
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).