我有两个组件与AuthorizeView:
MainLayout:
<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调用StateHasChanged()为NavMenu,但它不工作,也强制重载重定向,但它有一个奇怪的行为(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
方法被Renderer调用,触发一个渲染事件并更新它们的显示。
参见- https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0
我通过删除cascadingparameter来解决这个错误,并将它们替换为@inject AuthenticationStateProvider AuthenticationStateProvider
并且必须通过实例访问验证状态,如下所示:
var aut = await AuthenticationStateProvider.GetAuthenticationStateAsync();
if (aut.User.Identity.IsAuthenticated)
{
navigationManager.NavigateTo(ReturnUrl);
}