I am trying to create a very basic controller with three get methods Below are the three uri's for them
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?
You'd better to change your url like api/Movies/GetByName/{Id}
,api/Movies/GetById/{Name}
.
Then:
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With