Refresh Blazor layout

Viewed 191

I got 2 components with AuthorizeView :

MainLayout :

<AuthorizeView>
    <Authorized>
        <HeaderMenu />
        <NavMenu />
        <main class="w-full">
            @Body
        </main>
    </Authorized>
    <NotAuthorized>
        @Body
    </NotAuthorized>
</AuthorizeView>

NavMenu (contains the following piece of code) :

<AuthorizeView Roles="@(Role.SuperAdminRoleString + "," + Role.AdminRoleString)">
    <Authorized>
        <NavLink href="@ViewPaths.RegisterPage">
            <span >Register a user</span>
        </NavLink>
    </Authorized>
</AuthorizeView>

NavMenu is MainLayout's child, it's not shown if user is not authorized, after a successful login the AuthorizeView of MainLayout works correctly and shows NavMenu but NavMenu's AuthorizeView is not working unless I refresh the page

I tried to call StateHasChanged() for NavMenu from MainLayout but it's not working, also force reload on redirection but it has a weird behavior (NavMenu is appearing before reload)

2 Answers

I'm guessing at this point, but it looks like you probably don't have CascadingAuthenticationState set in App.razor.

Here's an example:

@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 instances set it up as a parameter

[CascadingParameter] private Task<AuthenticationState>? AuthenticationState { get; set; }

When it changes, their SetParametersAsync methods are called by the Renderer, triggering a render event and updating their display.

See - https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0

i solve this error by delete cascadingParametre and i replace them @inject AuthenticationStateProvider AuthenticationStateProvider and must be access to authenticate state by instace like this :

 var aut = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        if (aut.User.Identity.IsAuthenticated)
        {
            navigationManager.NavigateTo(ReturnUrl);
        }
Related