You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Layout页面跳转脚手架登录页触发NotFound问题求助

问题原因

Blazor的客户端路由和服务端路由是两套独立的规则:

  • 脚手架生成的Identity登录页属于ASP.NET Core Identity的服务端Razor Pages,不在Blazor客户端的路由注册表中,默认Blazor客户端跳转时会优先匹配自身路由表,匹配失败就会渲染NotFound内容
  • 你直接刷新页面时相当于向服务端发起了全新请求,服务端路由配置中包含Identity Razor Pages的规则,所以能正常返回登录页

解决方法

给NavigateTo方法添加第二个参数forceLoad: true,强制触发服务端跳转,不走Blazor客户端路由匹配逻辑即可,修改后的代码如下:

[Inject] private NavigationManager nav { get; set; }
// 注意你的原代码漏了AuthenticationStateProvider的注入,需要补上
[Inject] private AuthenticationStateProvider auth { get; set; }

protected override async Task OnInitializedAsync()
{
    var authState = await auth.GetAuthenticationStateAsync();
    var user = authState.User;
    if (!user.Identity.IsAuthenticated)
    {
        nav.NavigateTo("/Identity/Account/Login", forceLoad: true);
    }
}

如果是Blazor Web App的全局交互式渲染场景,更规范的实现是用AuthorizeRouteView组件配合自定义跳转组件完成全局未登录拦截,还能支持登录后自动回跳原访问页面:

  1. 先修改App.razor中的路由配置:
<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                <RedirectToLogin />
            </NotAuthorized>
        </AuthorizeRouteView>
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>
  1. 新建RedirectToLogin.razor组件:
@inject NavigationManager Nav
@code {
    protected override void OnInitialized()
    {
        Nav.NavigateTo($"/Identity/Account/Login?returnUrl={Uri.EscapeDataString(Nav.Uri)}", forceLoad: true);
    }
}

内容的提问来源于stack exchange,提问作者ChrisR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 05:06:04