How to deal with multiple Get requests with a single route pattern?

60 views Asked by At

let's say I have a movie controller to support two Get requests as below:

A. Get /movies/{movieId}
B. Get /movies/{genre}

movie id is Guid (e.g bff4c605-7ae4-76767-bcf8-12345f621bfd), not int type.

So when a request is made to the backend, movieId and genre are both of string, so how can I specify a requirement that if second url segment can be casted to Guid, then route it to Get A's action method, if it can only be casted to genre string then route it to the Get B's action method?

1

There are 1 answers

0
Mathias R. Jessen On

You can specify parameter constraints in the route pattern:

[Route(@"/movie/{id:guid}", Order = 1)]
public IActionResult MovieById(Guid id) {
    return Content($"MovieById={id}");
}

[Route(@"/movie/{genreId:int}", Order = 2)]
public IActionResult MovieByGenre(int genreId) {
    return Content($"MovieByGenre={genreId}");
}