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

Multiple actions were found that match the request error when adding a second GET action method to web api controller


I'm currently developing a Web API and I'm figuring out about how to add a new method inside my controller FilmsController which has to execute a LINQ query simply returning the related JSON to the user. Everything seems correct but when I try to call that API an error 404 appears. The API I'm trying to call is api/NewFilms, which should be correct.

Here is the method GetNewFilms inside FilmsController:

    public IQueryable<Film> GetNewFilms()
    {
        var query = from f in db.Films
                    orderby f.ReleaseYear descending
                    select f;

        return query;

    }

 // GET: api/Films
    public IQueryable<Film> GetFilms()
    {
        return db.Films;
    }

Solution

  • With the default routing configuration, web api controller allows to have only one GET action (without any parameters). If you have more than one GET actions, you will get a 500 error with message like

    Multiple actions were found that match the request

    If you need to have more than one GET actions, you may explicitly define a route pattern for those using Attribute routing.

    public class FilmsController : ApiController
    {
        [Route("api/Films/NewFilms")]
        public IEnumerable<string> GetNewFilms()
        {
           return new List<string> { "New Film 1","New Film 1"};
        }
    
        // GET: api/Films
        public IEnumerable<string> GetFilms()
        {
            return new List<string> { "Film 1","Film 2"};
        }
        public string GetFilm(int id)
        {
            return "A single film";
        }
    }
    

    Also, you may consider changing your return type from IQueryable to IEnumerable of your Dto ( instead of the entity class created by your ORM)