Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}"
);
like image 363
Bad Dub Avatar asked Oct 24 '25 02:10

Bad Dub


2 Answers

If your controller is named AccountController and the action method is named Profile, the pattern you can use is something like this:

pattern: {controller}/{action}/{name}

If that indeed doesn't work out, attributes on the controller class and methods should definitely work.

I suggest using the following attributes:

[ApiController]
[Route("[controller]/[action]")]
public class AccountController : ControllerBase
. . .
[HttpGet("{name}")]
public async Task<IActionResult> Profile(string name, string filter = null, int? page = null)

For this to work, you'll likely have to use the default controller router in your Program.cs/Startup.cs as app.MapDefaultControllerRoute();.

In general, I do suggest configuring routing on controllers and action methods instead of bloating the startup. It gives you much finer control over each of your actions and the routing you want for them.

like image 79
Aakash Sethi Avatar answered Oct 26 '25 14:10

Aakash Sethi


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)
{ .... }
like image 39
Bad Dub Avatar answered Oct 26 '25 14:10

Bad Dub