GoatInTheMachine
GoatInTheMachine

Reputation: 3773

asp.net WebAPI Two controllers with same routes but different verbs

I've got two controllers, each with a single action, with the idea that they both handle dynamic requests using a convention that is based on the url. One controller handles POSTs, the other handles GETs. Both controllers are tagged with [RoutePrefix("resource")], and both have a single action with [Route("{resourceName}")]. On one controller the action is tagged [HttpPost], the other [HttpGet]. However, when I make a request I get the error:

Multiple controller types were found that match the URL

I'm guessing this is because both controllers have routes that match source/*anything*, and routing doesn't bother to check the verb - if I put both actions in a single controller, everything works as expected. If possible I'd rather keep them separate though - is it possible to configure routing so that one handler can be used for POST, and one for GET, without them conflicting?

Upvotes: 0

Views: 937

Answers (1)

Nkosi
Nkosi

Reputation: 247088

You are correct both controllers have routes that match which is causing a conflict. Use partial classes if the plan is just to keep the code separate.

MyController.cs

[RoutePrefix("resource")]
public partial class MyController : ApiController { ... }

MyController_Get.cs

public partial class MyController {
    //GET resource/resourceName
    [HttpGet]
    [Route("{resourceName}")]
    public IHttpActionResult Get() { ... }
}

MyController_Post.cs

public partial class MyController {
    //POST resource/resourceName
    [HttpPost]
    [Route("{resourceName}")]
    public IHttpActionResult Post() { ... }
}

Upvotes: 3

Related Questions