3

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 ?

marcind
  • 52,944
  • 13
  • 125
  • 111
dohaivu
  • 2,038
  • 15
  • 17

1 Answers1

4

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

Alexander Zeitler
  • 11,919
  • 11
  • 81
  • 124
  • This way, it is not REST, it's RPC. I am looking for an attribute, such as [NeverBind]... but they have not existed yet, we can use this attribute to mark a method when we don't want to bind it to a URI. – dohaivu Feb 17 '12 at 12:39
  • When I ask this question, I wonder if I have more than a method which are prefixed by Get, how ASP.NET Web API bind them, and I want it REST way, not RPC alike. I google but no answer – dohaivu Feb 17 '12 at 12:46
  • Thanks you, after reading your blog post carefully I understand it. It is ASP.NET Web API convention, I have to follow it if I want it REST way – dohaivu Feb 17 '12 at 13:02
  • Yes, you can make it "REST style" using the routing. – Alexander Zeitler Feb 17 '12 at 13:06