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 ?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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
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
Yes, you can make it "REST style" using the routing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.