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

如何在Blazor的App.Razor中搭配使用Blazored.Modal与AuthenticationState

解决方案

正确的层级顺序应该是CascadingAuthenticationState作为最外层级联提供器,内部嵌套CascadingBlazoredModal,再放置路由相关的所有逻辑,示例代码如下:

<CascadingAuthenticationState>
    <CascadingBlazoredModal>
        <Router AppAssembly="@typeof(Program).Assembly" 
                AdditionalAssemblies="@lazyLoadedAssemblies" 
                OnNavigateAsync="@OnNavigateAsync">
            <Found Context="routeData">
                <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                    <NotAuthorized>
                        @if (!context.User.Identity.IsAuthenticated)
                        {
                            <!-- 原有未授权逻辑保留即可 -->
                        }
                    </NotAuthorized>
                </AuthorizeRouteView>
            </Found>
            <NotFound>
                <LayoutView Layout="@typeof(MainLayout)">
                    <p>抱歉,你访问的页面不存在。</p>
                </LayoutView>
            </NotFound>
        </Router>
    </CascadingBlazoredModal>
</CascadingAuthenticationState>

注意事项

  • 不要把CascadingBlazoredModal放在Found或者AuthorizeRouteView内部,路由切换时会触发组件重复挂载,导致模态框实例重复、页面重复渲染的问题
  • 级联提供器的嵌套顺序不需要调换,CascadingAuthenticationState在外层可以保证Blazored Modal内部的组件也能正常获取到授权状态
  • 如果你之前在MainLayout中也添加过CascadingBlazoredModal,需要删除,避免重复注册引发冲突
  • 配置完成后可先检查Program.cs中是否已经正确注册Blazored Modal服务:
builder.Services.AddBlazoredModal();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:15:00