ASP.NET Core Blazor routing

Route templates

Router组件在App.razor中开启到Razor组件的路由:

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        <p>Sorry, there's nothing at this address.</p>
    </NotFound>
</Router>

ASP.NET Core 5.0.1之后Router组件会带一个PreferExactMatches 参数,并设置为@true

@page条令会为生成的组件类中添加一个RouteAttribute。应用启动时,指定为Router的AppAssemby的assembly中的RouteAttribute信息会被扫描并收集。

运行时,RouterView组件会:

  • 从Router接收RouteData信息,信息中带有其他参数。
  • 将指定的组件按其布局进行渲染

若组件未使用@layout条令指定布局,那么可以指定一个DefaultLayout参数来作为其布局。Blazor工程模板指定MainLayout组件(Shared/MainLayout.razor)作为应用的默认布局。

组件可以通过多条@page条令来指定多个路由模板:

@page "/BlazorRoute"
@page "/DifferentBlazorRoute"

<h1>Blazor routing</h1>

如果URL要解析正确,需指定一个带有href<base>,如果时wasm,则在wwwroot/index.html;如果是server,则在Pages/_Host.cshtml

Provide custom content when content isn’t found

如果路由目标不存在,那么Router允许指定自定义内容.

Route to components from multiple assemblies

可以使用AdditionalAssemblies来指定不在AppAssembly范围内,额外需要添加的assembly:

<Router
    AppAssembly="@typeof(Program).Assembly"
    AdditionalAssemblies="new[] { typeof(Component1).Assembly }">
    @* ... Router component elements ... *@
</Router>

Route parameters

路由参数大小写不敏感。

下面是:

@page "/RouteParameter/{text}"

<h1>Blazor is @Text!</h1>

@code {
    [Parameter]
    public string Text { get; set; }
}

可选参数:

@page "/RouteParameter/{text?}"

<h1>Blazor is @Text!</h1>

@code {
    [Parameter]
    public string Text { get; set; }

    protected override void OnInitialized()
    {
        Text = Text ?? "fantastic";
    }
}

使用可选参数之后,访问/RouteParameter以及/RouteParameter/都能返回结果。

可以使用OnParametersSet而不是OnInitialized:

protected override void OnParametersSet()
{
    Text = Text ?? "fantastic";
}

路由參數不支持URL参数解析

Route constraints

为路由匹配指定额外约束(即类型):

@page "/user/{Id:int}"

<h1>User Id: @Id</h1>

@code {
    [Parameter]
    public int Id { get; set; }
}

下面是可用约束表:

  • bool
    • {active:bool}
    • true, FALSE
  • datetime
    • {dob:datetime}
    • 2016-12-31, 2016-12-31 7:32pm
    • Invariant culture matching
  • decimal
    • {price:decimal}
    • 49.99, -1,000.01
    • Invariant culture matching
  • double
    • {weight:double}
    • 1.234, -1,001.01e8
    • Invariant culture matching
  • float
    • {weight:float}
    • 1.234, -1,001.01e8
    • Invariant culture matching
  • guid
    • {id:guid}
    • CD2C1638-1638-72D5-1638-DEADBEEF1638, {CD2C1638-1638-72D5-1638-DEADBEEF1638}
  • int
    • {id:int}
    • 123456789, -123456789
    • Invariant culture matching
  • long
    • {ticks:long}
    • 123456789, -123456789
    • Invariant culture matching

类型即约束

Invariant culture matching啥意思?

约束可以和可选参数搭配:

@page "/user/{Id:int}/{Option:bool?}"

Routing with URLs that contain dots

(未完待续)