Search code examples
asp.net-mvcasp.net-web-apiasp.net-web-api2asp.net-routing

Web api different named actions cause Multiple actions error


I have web api 2 controller actions:

    [HttpGet]
    public Response<IEnumerable<Product>> Get()
    {
        ....(Get all products)
    }

    [HttpGet]
    public Response<Product> Get(int id)
    {
        ....(Get product by id)
    }

    [HttpGet]
    public Response<IEnumerable<Product>> Category(int id)
    {
        .... (Get products by category)
    }

I want to use this controllers with url:

http://localhost/api/product 

http://localhost/api/product/1

http://localhost/api/product/category/1 

But this url http://localhost/api/product/1 returns error,

Multiple actions were found that match the request

My config settings are like this:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApiWithAction",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Solution

  • You might be better off using attribute routing rather than global routing here. If you remove your global routes and define your routes on a per-action basis you should have no problems. For example, your routes could look like:

    [Route("api/product")]
    [Route("api/product/{id:int}")]
    [Route("api/product/category/{id:int}")]