【问题标题】:Create an alias for razor page为剃须刀页面创建别名
【发布时间】:2018-11-21 12:04:15
【问题描述】:

我正在玩asp.net razor pages。

我创建了默认的 asp.net core 2.1 应用程序,然后添加了 3 个页面:

default convention 页面将在路径中可用:

Page1 -> http://localhost/Page1
Page2 -> http://localhost/Folder/Page2
Page3 -> http://localhost/Page3

现在我想为 page2 添加一个别名,例如像这样:

Page1 -> http://localhost/Page1
Page2 -> http://localhost/Page2
Page2 -> http://localhost/Folder/Page2
Page3 -> http://localhost/Page3

如果没有adding-file-as-link,是否可以为此页面创建额外的路由/别名?

在@page 中指定页面路由

@page "/Page2"
@{
    ViewData["Title"] = "Page2";
}

<h2>Page2</h2>

将 page2 设为 http://localhost/Page2,但不设为 http://localhost/Folder/Page2 :(

【问题讨论】:

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


    【解决方案1】:

    您可以通过AddPageRoute(...) 实现此目的。这是您的情况的示例:

    services
        .AddMvc()
        .AddRazorPagesOptions(options =>
        {
            options.Conventions.AddPageRoute("/Folder/Page2", "/Page2");
        });
    

    【讨论】:

    • 不错的方法。我想我可以在我的剃须刀页面(继承 PageModel)中添加一个自定义属性(类似于 [AdditionalRoute("/Page2")])并通过 Startup.cs 中的反射将它们全部注册
    • 您可以考虑使用自定义约定来帮助解决此问题,具体取决于您的具体要求。例如,folder route model convention 将允许您编写代码来为多个页面自动执行上述解决方案。它有点高级,但可能值得付出努力。
    【解决方案2】:

    这个,可能会有所帮助。 https://github.com/T4MVC/T4MVC

    T4MVC 是一个用于 ASP.NET MVC 应用程序的 T4 模板,它创建了强类型帮助器,从而消除了在许多地方使用文字字符串。

    它将为您的视图生成文字路径,然后您可以从同一操作返回不同的视图。

    if (someCondition){
        return View(this.ViewNames.Page2)
    }
    else {
        return View(this.ViewNames.Folder_Page2)
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2021-04-25
      • 2020-11-11
      • 2023-03-17
      相关资源
      最近更新 更多