如何更新我的 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 和标记帮助程序。
如果页面也在帐户控制器中,您可以尝试使用:
<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"))
})
})