【问题标题】:Razor Pages routing with a prefix id带有前缀 id 的 Razor 页面路由
【发布时间】:2021-06-22 07:03:17
【问题描述】:

Razor Pages 有没有办法解决这个问题:

我有一个用户属于两家公司: 这些公司有 id 1 和 2

我的 Razor Pages 应用有这些页面:

Pages/Index.cshtml

Pages/Account/Login.cshtml
Pages/Account/Logout.cshtml

Pages/Dashboard/Index.cshtml
Pages/Employees/Index.cshtml

我想要实现的是:

对于这个页面,我想要常规路线

Pages/Index.cshtml

Pages/Account/Login.cshtml
Pages/Account/Logout.cshtml

对于这个页面,我希望路由是 /[COMPANY_ID]/Dashboard/[COMPANY_ID]/Employees

Pages/Dashboard/Index.cshtml
Pages/Employees/Index.cshtml

Pages/Index.cshtml 上,用户可以选择使用 id 1 或 2 访问公司的仪表板。

Pages/Dashboard/Index.cshtml我想创建一个指向Pages/Employees/Index.cshtml的链接,如何确保自动添加正确的[COMPANY_ID]

谢谢

【问题讨论】:

标签: c# asp.net-core razor-pages


【解决方案1】:

对于页面Pages/Dashboard/Index.cshtmlPages/Employees/Index.cshtml,我希望路由为/[COMPANY_ID]/Dashboard/[COMPANY_ID]/Employees

在 Pages/Dashboard/Index.cshtml 我想创建一个指向 Pages/Employees/Index.cshtml 的链接,如何确保自动添加正确的 [COMPANY_ID]?

要达到上述要求,可以尝试:

为您的页面添加和配置路由

services
    .AddRazorPages()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AddPageRoute("/Dashboard/Index", "/{id:int}/Dashboard/Index");
        options.Conventions.AddPageRoute("/Employees/Index", "/{id:int}/Employees/Index");
    });

Dashboard/Index.cshtml 页面中

@page
@model xxx.Pages.Dashboard.IndexModel
@{
    var hasId = HttpContext.Request.RouteValues.TryGetValue("id", out object id);
}

<h1>Dashboard Index</h1>

<a href=@(@hasId ? $"/{id}/Employees/Index" : "/Employees/Index")>Employees Index</a>

测试结果

【讨论】:

    猜你喜欢
    • 2019-03-21
    • 2018-02-17
    • 1970-01-01
    • 2014-04-30
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2023-03-24
    相关资源
    最近更新 更多