【问题标题】:Set a separate layout for public users为公共用户设置单独的布局
【发布时间】:2021-01-31 13:46:43
【问题描述】:

在 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-core blazor blazor-webassembly


    【解决方案1】:

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

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

    • AuthL.razor 用于身份验证用户。
    • PubL.razor 供公众用户使用。

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

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

    就是这样。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 2020-05-30
    • 2019-10-15
    • 1970-01-01
    相关资源
    最近更新 更多