如何自定义Blazor Wasm应用左上角的'Authorizing...'提示信息
我懂你说的这个情况——当用CascadingAuthenticationState、AuthorizeRouteView这类身份验证组件保护路由时,默认的"Authorizing..."提示确实有点生硬,而且不像初始加载提示那样改个index.html就能搞定。别担心,这个提示完全可以自定义,核心是利用AuthorizeRouteView提供的模板插槽来替换默认内容,下面给你两种实用方法:
方法一:直接修改AuthorizeRouteView的授权模板
通常你的App.razor里会有这样的路由结构:
<CascadingAuthenticationState> <Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> </Found> <NotFound> <LayoutView Layout="@typeof(MainLayout)"> <p>Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router> </CascadingAuthenticationState>
你只需要给AuthorizeRouteView添加<Authorizing>模板块,就能替换默认的提示内容:
<CascadingAuthenticationState> <Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"> <!-- 自定义授权中提示 --> <Authorizing> <div class="custom-authorizing"> <p>正在验证您的身份,请稍候...</p> <!-- 还可以添加加载动画,比如旋转的spinner --> <div class="spinner"></div> </div> </Authorizing> </AuthorizeRouteView> </Found> <NotFound> <LayoutView Layout="@typeof(MainLayout)"> <p>Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router> </CascadingAuthenticationState>
接着可以在wwwroot/css/app.css里给自定义类加样式,调整位置、字体甚至动画,摆脱默认的左上角布局:
.custom-authorizing { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; font-size: 1.2rem; color: #333; } .spinner { border: 4px solid rgba(0,0,0,0.1); width: 36px; height: 36px; border-radius: 50%; border-left-color: #007bff; animation: spin 1s linear infinite; margin: 10px auto; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
方法二:封装自定义授权组件(复用性更高)
如果项目里多个地方需要统一的授权提示风格,可以封装一个自定义组件,比如CustomAuthorizeRouteView.razor:
@inherits AuthorizeRouteView <Authorizing> <div class="custom-authorizing"> <p>🔍 正在验证身份,马上就好...</p> <div class="spinner"></div> </div> </Authorizing> <NotAuthorized> <!-- 顺便自定义未授权提示 --> <LayoutView Layout="@DefaultLayout"> <p>抱歉,您没有访问该页面的权限,请登录后重试。</p> </LayoutView> </NotAuthorized> <Authorized> <LayoutView Layout="@Layout ?? DefaultLayout"> @Body </LayoutView> </Authorized>
然后在App.razor里替换原有的AuthorizeRouteView即可:
<CascadingAuthenticationState> <Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <CustomAuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> </Found> <NotFound> <LayoutView Layout="@typeof(MainLayout)"> <p>Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router> </CascadingAuthenticationState>
这种方式能统一管理所有授权相关的提示,后期修改也更省心。
本质上就是利用AuthorizeRouteView的模板扩展能力,把默认的"Authorizing..."替换成你想要的内容和样式,完全能满足自定义需求。
内容的提问来源于stack exchange,提问作者Bronzato
相关产品推荐
相关产品推荐

