Blazor WASM 在未通过身份验证时重定向到登录 - 不显示布局

标签 blazor blazor-client-side blazor-webassembly

我有一个 Blazor WASM 有 2 种布局:

  1. 主布局
  2. 登录布局

我的主 Index 文件有一个 Authorized 属性

@page "/"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@attribute [Authorize]

当未授权被重定向到使用不同布局 (LoginLayout) 的“auth/login”时,我有一个简单的登录页面。

我面临的问题是,当我访问该应用程序时,我可以看到 MainLayout(页眉、导航左侧菜单、页脚)一秒钟,然后我看到我的登录空白屏幕。

这意味着因为 Index 是主路由并使用 MainLayout,所以需要大约 1 秒的时间来验证并重定向到我的登录页面,这就是布局的原因问题。

Is there a way to do the redirect before the MainLayout is rendered in the page? Or a way to not show the Layout HTML if the user is not authenticated?

最佳答案

尝试以下代码...我在使用个人身份验证托管的 WebAssembly 中对其进行了表面测试,它看起来不错。如果用户未通过身份验证,并且 Index 组件使用 Authorize 属性进行注释,他将被重定向到登录页面,而看不到 MainLayout。

将 MainLayout.razor 中的代码更改为以下内容:

@inherits LayoutComponentBase

<AuthorizeView>
    <Authorized>
        <div class="sidebar">
            <NavMenu />
        </div>

        <div class="main">
            <div class="top-row px-4 auth">
                <LoginDisplay />
                <a href="https://learn.microsoft.com/aspnet/" target="_blank">About</a>
            </div>

            <div class="content px-4">
                @Body
            </div>
        </div>

    </Authorized>
    <NotAuthorized>
        <div class="main">
            <div class="content px-4">
                @Body
            </div>
        </div>
   </NotAuthorized>
</AuthorizeView> 

测试上面的代码,看看它是否满足您的期望,然后相应地为您建模。请注意,您的登录组件应使用 @layout 指令进行修饰,以便 Blazor 将在您的自定义布局中显示登录组件。

在 DEFAULT MainLayout 之后为您的自定义布局建模...删除不需要的部分,并根据需要添加您自己的部分。

这个:@inherits LayoutComponentBase

还有这个:

   <div class="main">
                <div class="content px-4">
                    @Body
                </div>
   </div> 

必须...

关于Blazor WASM 在未通过身份验证时重定向到登录 - 不显示布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62921226/

相关文章:

c# - 基于 header 值的 ASP.Net Core Blazor : How to load different _Host. cshtml 文件

winforms - 在 Windows 窗体中向 blazor 混合添加回调

asp.net-core - 事件为 : Cannot convert lambda expression to intended delegate type 的代码中的 Blazor 可重用 RenderFragments

c# - 将 JsonConverterFactory 添加到 Blazor Webassembly 应用程序

c# - 检测导航事件 blazor webassembly

c# - Blazor HttpClient 卡在 GetAsync 中

c# - 重载圆圈组件

blazor - 如果 Blazor webassembly 中的 EditForm 组件为 "dirty",如何捕获

blazor - 在 blazor web-assembly 中通过 href 使用导航管理器

c# - 引用 Razor 类库时重复的基本路径