Is there a way to get a value from a route defined on the controller without adding the parameter to all http methods?
Example of what I'm trying to do.
calling localhost/api/test/client
[Route("api/{somevar}/[controller]")]
[ApiController]
public class ClientController : ControllerBase
{
private readonly MainContext fContext;
private string fSomeVar;
public ClientController(MainContext pContext)
{
fContext = pContext;
fSomeVar = somevar; <-- Is there a way to get "test" from the route?
}
// GET: api/Client
[HttpGet]
public async Task<ActionResult<IEnumerable<ClientDH>>> GetClients()
{
// use fSomeVar here.
}
// GET: api/Client
[HttpGet]
public async Task<ActionResult<IEnumerable<ClientDH>>> GetClients(string somevar)
{
// this works but I'm trying to avoid changing all the methods in all controllers.
}
}
CodePudding user response:
My suggestion is below:
1.You can use IHttpContextAccessor to get the route value from the http request, code as below:
public DemoController(IHttpContextAccessor httpContextAccessor)
{
fSomeVar = httpContextAccessor.HttpContext.Request.RouteValues["somevar"].ToString();
}
and in startup.cs, you need to configure:
services.AddHttpContextAccessor();
2.Demo:
[Route("api/{somevar}/[controller]")]
[ApiController]
public class DemoController : ControllerBase
{
private string fSomeVar;
public DemoController(IHttpContextAccessor httpContextAccessor)
{
fSomeVar = httpContextAccessor.HttpContext.Request.RouteValues["somevar"].ToString();
}
[HttpGet]
public async Task<IActionResult> Demo1()
{
try
{
return Ok("Id: " fSomeVar);
}
catch
{
return BadRequest();
}
}
[HttpGet("demo2/{id1}/{id2}")]
public async Task<IActionResult> Demo2(string id1, int id2)
{
try
{
return Ok("Id1: " id1 ", Id2: " id2 ", Id3: " fSomeVar);
}
catch
{
return BadRequest();
}
}
}
Result:

