Reputation: 461
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.
Upvotes: 2
Views: 1076
Reputation: 247133
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
Upvotes: 1
Reputation: 1026
You can define the route for it using route attribute, as far as I understand you don't want to have 3 different controllers in order to avoid code duplication so you may try something like:
namespace Controllers
{
[ApiController]
[Route("api/stateusers")]
public class StateUsersController : ControllerBase
{
public StateUsersController()
{
}
// GET api/stateusers/getusers/{state}
[HttpGet]
[Route("getusers/{state}")]
public async Task<IActionResult> GetUsers(string state)
{
//Implement your logic
}
//Or
// GET api/stateusers/{state}
[HttpGet]
[Route("{state}")]
public async Task<IActionResult> GetUsersByState(string state)
{
//Implement your logic
}
}
}
Note: I would advise you to have a look on the following website REST Resource Naming Guide where you can check the guidelines for RESTful APIs naming.
Upvotes: 0