Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API binding method

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 ?

like image 318
dohaivu Avatar asked Dec 30 '25 11:12

dohaivu


1 Answers

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).

like image 76
Alexander Zeitler Avatar answered Jan 02 '26 15:01

Alexander Zeitler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!