I have a simple ASP.NET Core MVC controller action method defined as:
public class MyMVCController : Controller
{
public async Task<IActionResult> MyAction(String usrid)
{
// ...
}
}
When I call it using this URI:
https://localhost:6009/MyMVC/MyAction/073214df
My action gets invoked and I get return back, but the parameter usrid
is always null. What am I doing wrong?
UPDATE
@Jackdaw's first solution, change parameter name from usrid
to id
worked for me. However, the ones with attributes don't. While the parameter does get passed in, the action will fail because the accessToken
somehow returns null in the line below. This is not the case in the first solution.
[Route("MyMVC/MyAction/{usrid?}")]
public async Task<IActionResult> MyAction(String usrid)
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// ...
}
Finally, I figured out how to get the attribute based routing solutions to work - adding another attribute [Authorize]
to the action method. Don't ask me why I have to do this and why I don't in the usrid
/id
solution.
It`s because the default route pattern has the following definition:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Therefore, if change the method parameter name to id
it will work:
public async Task<IActionResult> MyAction(String id)
Or you can apply the following route attribute to the method:
[Route("MyMVC/MyAction/{usrid?}")]
public async Task<IActionResult> MyAction(String usrid)
{
// ...
}