MVC 持久化路由数据值

问题描述

我如何使用 MVC,以便一旦用户登录站点,它就会遵循 URL 模式

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

我在 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?}");
        });

如果我手动输入页面按预期加载的 URL,这工作正常。 但是一旦使用路由值在网站上导航就会丢失,它会认返回

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

如何保留 url 路由“用户名”值?

使用 .Net 5 和标签助手。

解决方法

如果页面也在Account Controller中,您可以尝试使用:

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

结果: enter image description here

或者你可以使用js获取当前url,然后从中获取用户名并将其添加到链接href中。这是一个更改所有链接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"))
        })
        
    })

结果: enter image description here