gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:54:58 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com