可以使用Blazor自带的CascadingAuthenticationState组件来获取当前用户的信息,而不需要使用IHttpContextAccessor。具体步骤如下:
@inject AuthenticationStateProvider AuthenticationStateProvider
@code {
private Task AuthStateTask;
protected override async Task OnInitializedAsync()
{
AuthStateTask = AuthenticationStateProvider.GetAuthenticationStateAsync();
}
}
public Task HandleAsync(AuthorizationHandlerContext context)
{
var authState = await AuthStateTask;
var user = authState.User;
// 判断用户是否登录,并处理其他授权逻辑
}