如何在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
相关产品推荐
相关产品推荐

