在使用InteractiveServer和 ASP.NET Identity的 .NET 10 Blazor Web应用中,为什么 /Account/Login会短暂显示一次,随后又消失?

编程语言 2026-07-12

我正在使用ASP.NET Core Identity构建一个Blazor .NET 10 Web应用(交互式服务器组件)。

我的应用具有以下行为:

  • 导航到 /Account/Login 会短暂渲染登录页
  • 然后页面消失(闪烁),要么重定向,要么变成空白页 / 未找到
  • 登录表单从未持续显示足够时间以提交

这仅在应用变得 可交互 时发生。

如果我禁用交互性或正常呈现,登录页可以工作。

我有一个使用以下内容的.NET 10 Blazor Web应用:

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

builder.Services.AddIdentityCore<ApplicationUser>()
    .AddEntityFrameworkStores<NexaPlatformDbContext>()
    .AddSignInManager()
    .AddDefaultTokenProviders();

中间件:

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorComponents<App>()
   .AddInteractiveServerRenderMode();

登录组件:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <RedirectToLogin />
                </NotAuthorized>
            </AuthorizeRouteView>
        </Found>

        <NotFound>
            <p>Not found</p>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

路由配置:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <RedirectToLogin />
                </NotAuthorized>
            </AuthorizeRouteView>
        </Found>

        <NotFound>
            <p>Not found</p>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

观察到的行为

当导航到 /Account/Login 时,登录页会渲染一瞬间,然后消失。

在某些情况下我还看到:

AmbiguousMatchException: The request matched multiple endpoints

当存在多个登录路由时。

修正之后,闪烁的行为仍然存在。

  1. 只有一个组件具有 @page "/Account/Login"
  2. 登录页有 [AllowAnonymous]
  3. app.MapAdditionalIdentityEndpoints() 已移除
  4. 预渲染禁用(InteractiveServerRenderMode(prerender:false)
  5. Cookies和重定向看起来正常
  6. 直接访问时登录端点工作

我该如何解决这个问题?

解决方案

好吧,找到了一个变通办法:在app.razor中不指定渲染模式,只在需要将交互模式设为interactiveserver的页面上进行指定。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章