简体   繁体   中英

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?

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() { ... }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM