[英]Refresh Blazor layout
我使用 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://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0
我通過刪除 cascadingParametre 解決了這個錯誤,我將它們替換為@inject AuthenticationStateProvider AuthenticationStateProvider
並且必須通過如下方式訪問以驗證 state:
var aut = await AuthenticationStateProvider.GetAuthenticationStateAsync();
if (aut.User.Identity.IsAuthenticated)
{
navigationManager.NavigateTo(ReturnUrl);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.