Route conflict in ASP.NET WebAPI

Viewed 462

I have two different controllers and each one with its configured routes. To explain my problem, I will exemplify:

ProdutoController

[Route("v1/empresas/{idConexao}/produtos/{id}")]

ProdutoCategoriaController

[Route("v1/empresas/{idConexao}/produtos/categorias")]

When doing a GET on the route "v1/empresas/{idConexao}/produtos/categorias" using postman I get the following error message:

Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL

But if I comment on route "v1/empresas/{idConexao}/produtos/{id}" I can do a get on route "v1/empresas/{idConexao}/produtos/categorias" and vice versa.

Does anyone know how i can solve this problem? I see no sense in this error

1 Answers

The problem is tath both path match same route if {id} attribute is a string.

Asp.net cannot difference of "categories" is a id param or part of path

To solve this, you can use route constrains, to make more especific path.

For example, you can define type of param id like a int or guid.

[Route("v1/empresas/{idConexao}/produtos/{id:int}")]

this way you can call api with and responses should be those:

  • v1/empresas/{idConexao}/produtos/categorias -- Ok 200
  • v1/empresas/{idConexao}/produtos/1 --> OK 200
  • v1/empresas/{idConexao}/produtos/anotherString --> NotFound 400

You can read about route constrains here: https://docs.microsoft.com/es-es/aspnet/core/fundamentals/routing?view=aspnetcore-3.1#route-constraint-reference

I hope this is usefull!

Best regards

Related