Barnsley
Barnsley

Reputation: 181

How to persist route data value in ASP.NET Core MVC

How can I work update my MVC application so that once a user is logged into the site it follows the URL pattern

pattern: "{username}/{controller=Home}/{action=Index}/{id?}");

I have added the following end point in Startup.cs Configure()

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            endpoints.MapControllerRoute(
                name: "username",
                pattern: "{username}/{controller=Home}/{action=Index}/{id?}");
        });

This is working fine if I manually type in the URL the pages load as expected, but as soon as navigate around the site using the route value is lost and it defaults back to

pattern: "{controller=Home}/{action=Index}/{id?}");

How can I persist the URL route 'username' value?

I'm using .NET 5 and Tag Helpers.

Upvotes: 2

Views: 121

Answers (1)

Yiyi You
Yiyi You

Reputation: 18139

If the pages are also in the Account Controller,you can try to use:

<a class="btn btn-primary" href="Edit">Edit </a>

result: enter image description here

Or you can use js to get the current url,then get username from it and add it into a link href.Here is a demo to change all the links href: html:

<a class="btn btn-primary" asp-area="" asp-controller="Account" asp-action="Edit" >Edit </a>
<a class="btn btn-primary" asp-area="" asp-controller="Account" asp-action="Create">Create </a>

js:

 $(function () {
        var s = window.location.href.split("/")[3];
        $("a").each(function () {
            $(this).attr("href", "/" + s + $(this).attr("href"))
        })
        
    })

result: enter image description here

Upvotes: 0

Related Questions