0

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;
    }
Shyju
  • 214,206
  • 104
  • 411
  • 497
Gab
  • 87
  • 3
  • 7
  • Possible duplicate of [Web Api Routing for multiple Get methods in ASP.NET MVC 4](http://stackoverflow.com/questions/12775590/web-api-routing-for-multiple-get-methods-in-asp-net-mvc-4) – Ilya Sulimanov May 14 '16 at 21:57

1 Answers1

1

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)

Shyju
  • 214,206
  • 104
  • 411
  • 497