Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-routing

why exception throws as Multiple actions were found that match the request


I'm new to ASP.NET MVC, below is my api controller:

// API controller named Movie

[HttpGet]
public JsonResult Get()
{
    ....       
}

[HttpGet]
public JsonResult Get([FromQuery]int id)
{
  ....         
}
[HttpGet]
public JsonResult Get([FromQuery]string title, [FromQuery]string category)
{
  ....         
}

then when I start the appication and routed to localhost/api/movie/123, it threw an exception which is Multiple actions were found that match the request

but only the first action method match, since there is only one parameter?


Solution

  • You have a route conflict because all those actions map to the same route and the route table does not know which to choose.

    Routes need to be unique per action to avoid route conflicts.

    In order for localhost/api/movie/123 to match Get(int id) action the route template would need to look like

    //GET api/movie/123
    [HttpGet("{id:int}")]
    public JsonResult Get(int id) {
        //....         
    }
    

    Note the removal of the [FromQuery] and also the use of a route constraint {id:int} on the id route parameter

    The second action should now not conflict with the first

    //GET api/movie?title=someTitle&category=someCategory
    [HttpGet]
    public JsonResult Get([FromQuery]string title, [FromQuery]string category) {
        //....         
    }
    

    Reference Routing to controller actions in ASP.NET Core

    Reference Routing in ASP.NET Core