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}"
);
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.
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)
{ .... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With