Blazor @page 路由 url 使用变量定义

Mur*_*NER 24 asp.net-core blazor blazor-server-side asp.net-blazor

我有一个关于 Blazor 服务器端的问题。

我想@page用变量或属性定义路由 url。

我现在可以使用以下默认方法

@page "/route-url"

<h1>Page Test</h1>

@code {
    
}
Run Code Online (Sandbox Code Playgroud)

但我想使用如下方法

@page MenuItem.Role

<h1>Page Test</h1>

@code {
    
}
Run Code Online (Sandbox Code Playgroud)

我尝试了上面的方法然后抛出异常。就像下面的异常一样。

C:\Projects\TestBlazorProject\Pages\TestPage.razor(1,7): error RZ1016: The 'page' directive expects a string surrounded by double quotes. [C:\Projects\TestBlazorProject\TestBlazorProject.csproj]
Run Code Online (Sandbox Code Playgroud)

如何@page使用任何不同的变量或任何类属性定义路由 url?

use*_*357 42

这可以做到吗?

是的

如何?

页面文件

@attribute [Route(PageRoute.TaskList)]

<div>PAGE HTML HERE</div>

@code{ ... }
Run Code Online (Sandbox Code Playgroud)

页面路由.cs:

public static class PageRoute
{
    public const string TaskList = "/route-url";
}
Run Code Online (Sandbox Code Playgroud)

解释

page 指令被编译为属性,并且具有与 C# 属性相同的限制。

您可以将@attribute[Route]属性一起使用,并使用字符串连接而不是字符串插值来定义路由常量,因为这是 C# 编译器支持的。

为什么有人会这样做?

这是一种很好的编码实践,因为您没有在多个位置硬编码页面/组件名称,而只是在一个位置硬编码。
因此,有一天,当您的经理要求将页面名称“Earth”更改为“Planet3”时,
您只需将其更改为 1 个位置,并且 98% 确定您的应用程序不会因此而崩溃。


MrC*_*tis 9

@page不是 C#,而是 Razor 语言。Razor 文件在编译过程中被预编译成 C# 文件。

例如,这是 Index.razor 的 C# 预编译文件 (Index.razor.g.cs) 的重要部分:

[Microsoft.AspNetCore.Components.RouteAttribute("/")]
public partial class Index : Microsoft.AspNetCore.Components.ComponentBase
{
    #pragma warning disable 1998
    protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
    {
        __builder.AddMarkupContent(0, "<h1>Hello, world!</h1>\r\n\r\nWelcome to your new app.\r\n\r\n");
        __builder.OpenComponent<Blazor.Starter.Shared.SurveyPrompt>(1);
        __builder.AddAttribute(2, "Title", "How is Blazor working for you?");
        __builder.CloseComponent();
    }
    #pragma warning restore 1998
}
Run Code Online (Sandbox Code Playgroud)

注意,这@page已成为编译时属性[Microsoft.AspNetCore.Components.RouteAttribute("/")]。它在编译时是固定的,您无法在运行时更改它。

路由以这种方式设置是因为当应用程序通过搜索应用程序集来查找具有属性的任何组件类来加载应用程序时,路由器会构建一个路由映射(本质上是路由 url/组件类对的字典)Route。在路由事件中,它读取新的 url,找到组件类并将其加载到布局中。任何变量(大括号中的内容)都会作为 传递到组件中Parameters

您还没有弄清楚下面的行应该做什么:

@page MenuItem.Role

  1. 您想捕获路由中提供的变量吗MenuItem.Role
  2. 您想将此页面的路由设置为 中的值吗MenuItem.Role

如果为 1,则其他答案都适合您。如果是 2,您需要考虑编写自己的路由器。这里的主题超出了简单的答案。

  • 这个解决方案非常有效!如果您有 *CSHMLT* 文件,则必须使用以下属性:`[Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadata("RouteTemplate", "/YourPageUrl")]` (3认同)