Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple get methods in .net core 3.1 web api

I am trying to create a very basic controller with three get methods Below are the three uri's for them

  1. GET /movies - gets all movies.
  2. GET /movies?name={name}` - finds all movies matching the specified name
  3. Get /Movies/{Id} - Find movie By Id

My code for the controller is as below

[Route("api/[controller]")]
[ApiController]
public class MoviesController : ControllerBase
{
    private readonly IMoviesService moviesService;

    public MoviesController(IMoviesService moviesService)
    {
        this.moviesService = moviesService;
    }
    
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var result = await moviesService.GetMoviesAsync();
        return Ok(result);
    }
    
    [HttpGet]
    public async Task<IActionResult> GetByName([FromQuery(Name = "name")] string name)
    {
        var result = await moviesService.GetMoviesByNameAsync(name);
        return Ok(result);
    }

    [HttpGet("{Id}", Name = "GetById")]
    public async Task<IActionResult> GetById(Guid Id)
    {
        var result = await moviesService.GetMovieById(Id);
        return Ok(result);
    }       

}

When i send the request to GetById by api/movies/31234567-89ab-cdef-0123-456789abcdef then it works but for api/movies and api/movies?name=Test i get below error

The request matched multiple endpoints. Matches: MoviesController.Get and MoviessController.GetByName

Can anyone please suggest me what is the best way to implement such scenario in web api .net core 3.1 considering best practises?

like image 505
Nishant Shrivastava Avatar asked Sep 30 '20 11:09

Nishant Shrivastava


1 Answers

You'd better to change your url like api/Movies/GetByName/{Id},api/Movies/GetById/{Name}.

Then:

  1. GET /movies - gets all movies.
  2. GET /movies/GetByName/{name}` - finds all movies matching the specified name
  3. Get /Movies/GetById/{Id} - Find movie By Id

When add other action ,you can also add action name to route,it can help you avoid The request matched multiple endpoints.

Here is a demo:

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            return Ok();
        }

        [HttpGet("GetByName/{name}")]
        public async Task<IActionResult> GetByName(string name)
        {
            return Ok();
        }

        [HttpGet("GetById/{Id}")]
        public async Task<IActionResult> GetById(Guid Id)
        {
            return Ok();
        } 

result: enter image description here

like image 62
Yiyi You Avatar answered Sep 21 '22 17:09

Yiyi You