Ad

Invoke ASP.Net Core MVC Controller Action With Parameter Doesn't Work

- 1 answer

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?

Ad

Answer

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)
{
    // ...
}
Ad
source: stackoverflow.com
Ad