我通过 AuthorizeView 获得了 2 个组件:
主要布局:
<AuthorizeView>
<Authorized>
<HeaderMenu />
<NavMenu />
<main class="w-full">
@Body
</main>
</Authorized>
<NotAuthorized>
@Body
</NotAuthorized>
</AuthorizeView>
NavMenu(包含以下代码):
<AuthorizeView Roles="@(Role.SuperAdminRoleString + "," + Role.AdminRoleString)">
<Authorized>
<NavLink href="@ViewPaths.RegisterPage">
<span >Register a user</span>
</NavLink>
</Authorized>
</AuthorizeView>
NavMenu 是 MainLayout 的子项,如果用户未被授权则不会显示,成功登录后 MainLayout 的 AuthorizeView 正常工作并显示 NavMenu 但 NavMenu 的 AuthorizeView 不工作,除非我刷新页面
我试图从 MainLayout 为 NavMenu 调用 StateHasChanged() 但它不起作用,也强制重新加载重定向但它有一个奇怪的行为(NavMenu 在重新加载之前出现)
最佳答案
我现在猜测,但看起来您可能没有在 App.razor
中设置 CascadingAuthenticationState
。
这是一个例子:
@namespace Blazr.Auth
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<Authorizing><h3>Trying to authorize you.</h3></Authorizing>
<NotAuthorized><h3>Sorry mate, you can't go here now!</h3></NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
AuthorizeView
实例将其设置为参数
[CascadingParameter] private Task<AuthenticationState>? AuthenticationState { get; set; }
当它发生变化时,渲染器调用它们的 SetParametersAsync
方法,触发渲染事件并更新它们的显示。
参见 - https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0
关于c# - 刷新 Blazor 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72868131/