Search code examples
c#.netasp.net-web-api2asp.net-web-api-routingattributerouting

Attribute routing in different controllers results in "Multiple controller types were found that match the URL"


I am developing an application in .NET WebApi2 but I have a problem with the attribute routing when trying to split a controller in two. Both controllers have an action that is routed via /api/users/ but one is a GET and the other a POST.

But I am getting the exception Multiple controller types were found that match the URL. In a way it makes sense because it's true what the exception says, but as they have a different HttpMethod I'd expect this to work.

When putting both actions into the same controller, it works fine, which tells me that the framework does take the HttpMethod into account when matching the URI against an action.

So is there a way to make this work or am I forced to put both actions into the same controller?

[RoutePrefix("api/users")]
public class UserManagementController : ApiController 
{
    [HttpPost]
    [Route]
    public async Task<IHttpActionResult> CreateUser([FromBody] CreateUserInputModel input) 
    {
        // ...
    }
}

[RoutePrefix("api/users")]
public class UserController : ApiController
{
    [HttpGet]
    [Route]
    public async Task<IHttpActionResult> GetAllUsers() 
    {
        // ...
    }
}

Solution

  • Routing is what determines what controller to use. But there is nothing built into routing (in Web API 2, anyway) that can tell the difference between a Get and a Post. By the time the request is handed off to the action invoker, it is already too late to go back and change the controller.

    So, to fix this the best option is to use IHttpRouteConstraint to put further criteria on the route whether to match HttpGet or HttpPost and then configure it accordingly.

    See Multiple Controller Types with same Route prefix ASP.NET Web Api for an example.