Search code examples
c#apicontrollerrefactoringurl-routing

In C#, is it possible to have a separate Router and Controllers?


I'm currently refactoring an ASP.NetCore 2.18.0 project with a Controller which has far too many responsibilities. I actually want to divide it into 4 separate Controllers. The problem is, I don't want to burden the consumers with updating their solutions, so while I want the logic to live on the different controllers, I want to keep the routes as they currently are:

ContractListController

  • /api/v1.0/Contract
  • /api/v1.0/Contract/listAll/{customerReference}
  • /api/v1.0/Contract/listOne/{customerReference}/{contractNumber}

ContractFactoryController

  • /api/v1.0/Contract/Vollmacht
  • /api/v1.0/Contract/Gripop
  • /api/v1.0/Contract/Sepa

ContractLinkController

  • /api/v1.0/Contract/renew/{customerReference}/{contractNumber}
  • /api/v1.0/Contract/renewlnk/{contractNumber}

ContractDocuSignController

  • /api/v1.0/Contract/dsReturn
  • /api/v1.0/Contract/dsReturn/{contractNumber}/{sp}/{c1}/{c2}/{c3}

Is there a way I can create a router which will direct Http requests to the appropriate Controller instead of using annotations on the Controller?

FWIW, I can't find MapControllerRoute anywhere in the project. The Controller has [Route("api/v{version:apiVersion}/[controller]")] and then methods have attributes like [Route("listAll/{customerReference}")]


Solution

  • This was actually simpler than I expected.

    My original controller class had attributes like this:

    [RequireHttps]
    [Authorize]
    [ApiController]
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    public class ContractController : Controller
    {
      // whatever
    }
    

    All I needed to do was:

    1. Create the four controllers, each with the same Attributes and extending Controller
    2. Replace [Route("api/v{version:apiVersion}/[controller]")] with [Route("api/v{version:apiVersion}/Contract")]
    3. Delete the original controller.