首页 > 解决方案 > 为公共用户设置单独的布局

问题描述

在 Blazor WebAssembly 中,如何为登录用户和未登录用户提供单独的布局?

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
               <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                    <Authorizing>
                        <text> Authotizing ...</text>
                    </Authorizing>
                </AuthorizeRouteView>
          
           /*Something like this:*/
             <NotAuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(NotAuthorizedLayout)">
                    <Authorizing>
                        <text> Authotizing ...</text>
                    </Authorizing>
                    <NotAuthorized>
                        <text></text>
                    </NotAuthorized>
                </NotAuthorizeRouteView>
        </Found>
        <NotFound>

            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>

        </NotFound>
        
    </Router>

或者换句话说,如何在 Blazor 中的不同布局之间切换?

标签: c#asp.net-coreblazorblazor-webassembly

解决方案


目前不存在第二个参数AuthorizeRouteView来为“公共”用户设置特定布局。但是存在一个简单的解决方案,这就是您可以轻松处理这种情况的方法。

假设您有 2 个布局准备好申请 auth 和 pub 用户:

  • AuthL.razor对于身份验证用户。
  • PubL.razor对于公共用户。

此时,您可以重写MainLayout.razor使用AuthorizeView 组件来设置正确的布局:

@inherits LayoutComponentBase
<AuthorizeView>
    <Authorized>
        <AuthL Body=@Body />            
    </Authorized>
    <NotAuthorized>
        <PubL Body=@Body />            
    </NotAuthorized>
</AuthorizeView>

就这样。


推荐阅读