Detilium Detilium - 2 months ago 12
ASP.NET (C#) Question

Routing using a named parameter in the request URL

I'm trying to navigate to the route

/Account/UserProfile/{username}
, but I'm not sure that I've configured the routes correctly. Or rather, I'm not sure what to add to the route table to make this route work.

Here's the action method:

public IActionResult UserProfile(string username)
{
// Do something
}


Which is a simple GET method that I'm hitting correctly. My problem is that even though I supply a string in the url, like:
/Account/UserProfile/MyUsername
, the string
MyUsername
is not being sent to my controller.

I only have the standard route already added when creating the application. What do I need to add to allow these routes to work?

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

Answer

you are missing username parameter in your route. the parameter names need to match

app.UseMvc(routes => {
    routes.MapRoute(
        name: "UserProfile",
        template: "Account/UserProfile/{username}",
        defaults: { controller = "Account", action = "UserProfile" });

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});
Comments