Search code examples
.net.net-coreasp.net-core-webapiasp.net-core-routing

.Net Core Web API, create a routing logic to different controllers with same route prefix based on a value


I have to create a routing logic for a .Net Core 3.0 Web API project that routes to different controllers with same route prefix given a value.

Example: I have controllers based on states.

StateUsersCOController
StateUsersCAController
StateUsersWAController

and such.

They all implement the same method such as:

GetUsers();

What I want to achieve is my request routed to a related controller based on state information such as:

api/StateUsers/CA

or

api/StateUsers?state=CA

or

api/StateUsers and Request Header has the state Information such as State:CA

What I can come up is creating a controller called StateUsers, capture the state value in one of the provided ways mentioned above and redirect the request to related controller, but I want to avoid redirection and achieve this is routing level. Can you guys please provide a better way to do this.


Solution

  • Attribute routing with fixed route templates should be able to uniquely differentiate the controllers

    [ApiController]
    [Route("api/StateUsers/CO")]
    public class StateUsersCOController : Controller {
        //GET api/StateUsers/CO
        [HttpGet]
        public IActionResult GetUsers() {
            //...
        }
    }
    
    [ApiController]
    [Route("api/StateUsers/CA")]
    public class StateUsersCAController : Controller {
        //GET api/StateUsers/CA
        [HttpGet]
        public IActionResult GetUsers() {
            //...
        }
    }
    
    [ApiController]
    [Route("api/StateUsers/WA")]
    public class StateUsersWAController : Controller {
        //GET api/StateUsers/WA
        [HttpGet]
        public IActionResult GetUsers() {
            //...
        }
    }
    

    Note the removal of GetUsers from the route to allow for a more simplified RESTFul URL.

    If you insist on including GetUsers in the URL, then include it in the rout template.

    Reference Routing to controller actions in ASP.NET Core

    Reference Routing in ASP.NET Core