【问题标题】:MVC persist route data valueMVC 持久化路由数据值
【发布时间】:2021-05-16 11:44:51
【问题描述】:

我如何使用 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 和标签助手。

【问题讨论】:

  • “但是一旦使用路由值在站点中导航就丢失了”,这是什么意思?当你没有用户名的路由时,它会转到默认路由?
  • @YiyiYou 例如,如果我手动导航到 /{myusername}/account/myprofile 这将起作用,并且我在该页面上有一个链接来编辑我的帐户。例如 Edit 而不是导航到 /{myusername}/account/edit 它只会导航到 /account/edit。所以我想知道如何保持 /{username}/ 路由值。

标签: asp.net-mvc asp.net-core .net-5 asp.net5


【解决方案1】:

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

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

结果:

或者你可以使用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"))
        })
        
    })

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-21
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多