使用 OnInitializedAsync 时 Blazor 身份验证失败

Blazor Authentication Fails when using OnInitializedAsync

我有以下剃须刀组件

page "/test"
@using Microsoft.AspNetCore.Components.Authorization
@inject HttpClient Http

<h3>TestAuthPage</h3>

<AuthorizeView Roles="admin">
    <Authorized>
        Hello
    </Authorized>
    <NotAuthorized>
        Not Auth
    </NotAuthorized>
</AuthorizeView>

@code {

    protected override async Task OnInitializedAsync()
    {
        var f = await Http.GetFromJsonAsync<List<string>>("api/test");
    }
}

这会在浏览器中引发错误,因为它在调用 api

时给出 401

但是如果我这样做

@page "/test"
@using Microsoft.AspNetCore.Components.Authorization
@inject HttpClient Http

<h3>TestAuthPage</h3>

<AuthorizeView Roles="admin">
    <Authorized>
        Hello
        @if(sss().Result)
        {}
    </Authorized>
    <NotAuthorized>
        Not Auth
    </NotAuthorized>
</AuthorizeView>

@code {
    public async Task<bool> sss()
    {
        var f = await Http.GetFromJsonAsync<List<string>>("api/test");
        return true;
    } 
}

正确调用了api控制器。

这到底是怎么回事?确定 OnInitializedAsync() 是初始化页面的标准方法吗?

好的,我似乎已经解决了这个问题。如果我添加一个 AuthenticationState 参数,然后在方法中等待它,那么 Controller 被调用正常并且我在控制器端进行了身份验证。我不知道为什么会这样,但我认为这一定是时机问题?如果有人知道为什么会这样,请告诉我...

@page "/test"
@using Microsoft.AspNetCore.Components.Authorization
@inject HttpClient Http

<h3>TestAuthPage</h3>

<AuthorizeView Roles="admin">
    <Authorized>
        Hello
        @if(sss().Result)
        {}
    </Authorized>
    <NotAuthorized>
        Not Auth
    </NotAuthorized>
</AuthorizeView>

@code {
    [CascadingParameter]
    public Task<AuthenticationState> AuthState{ get; set; }

    protected override async Task OnInitializedAsync()
    {
        var t = await AuthState;
        var f = await Http.GetFromJsonAsync<List<string>>("api/test");
    }

}