如何在 ASP.NET Core MVC 中持久保存路由数据值

问题描述 投票:0回答:1

如何更新我的 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 和标记帮助程序。

asp.net-core asp.net-core-mvc url-routing .net-5 asp.net-core-5.0
1个回答
0
投票

如果页面也在帐户控制器中,您可以尝试使用:

<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

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.