I am trying to find a solution to get a parameter (username) from a GET request. This parameter can be sent either by query or in the path (both method are valid). Valid examples:
GET /users/my_name
GET /users?login=my_name
Using .NET 6 I found a solution to get this parameter from path:
[HttpGet("{login?}")]
public IActionResult Get(string login)
{
if (login == null)
return GetAllusers();
return GetUserByLogin(login);
}
or to get this parameter from query:
[HttpGet]
public IActionResult Get(string login)
{
if (login == null)
return GetAllusers();
return GetUserByLogin(login);
}
But I have no solution that will fill the login parameter in both cases. Is there a generic solution where I could have this parameter filled in both cases?
I found a workaround that is given bellow but I am not sure this is the best way to handle this problem:
[HttpGet("{login_path?}")]
public IActionResult Get(string login_path, string login)
{
string user = (login_path != null) ? login_path : login;
if (user == null)
return GetAllusers();
return GetUserByLogin(user);
}
CodePudding user response:
When path parameter is null read the value from query string using HttpContext.Request.Query
.
[HttpGet("{login?}")]
public IActionResult Get(string login)
{
login ??= HttpContext.Request.Query["login"];
if (login == null)
return GetAllusers();
return GetUserByLogin(login);
}