Search code examples
c#asp.net-coreasp.net-mvc-routing

Routing to controller actions in ASP.NET Core with String parameter


I want to set up the routing in my project so that I can have a URL like /Account/Profile/FrankReynolds instead of having to do /Account/Profile?name=FrankReynolds. If I try and hit the URL /Account/Profile/FrankReynolds the name parameter is coming through as NULL.

This is the IActionResult on the Account controller.

public async Task<IActionResult> Profile(string name, string filter = null, int? page = null)
{ .... }

In my Program.cs I am currently using the following:

app.MapControllerRoute(
    name: "AccountDefault",
    pattern: "{controller=Account}/{action=Profile}/{name}"
);

Solution

  • I had to update the IActionResult with the HttpGet attribute that included the URL path and the parameter name and also add the FromRoute attribute just before the name parameter.

    [HttpGet("Account/Profile/{name}")]
    public async Task<IActionResult> Profile([FromRoute] string name, string filter = null, int? page = null)
    { .... }