要解决此问题,您需要始终使用异步方法来设置身份验证状态,并且需要使用 Task.FromResult 方法以异步方式返回结果。
以下是一个示例 CustomAuthenticationStateProvider 类,该类实现了 IAuthenticationStateProvider 接口,并在服务器端上工作:
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
private User _user;
public override async Task GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity();
if (_user != null)
{
identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, _user.UserName),
}, "apiauth_type");
}
return await Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity)));
}
public void MarkUserAsAuthenticated(User user)
{
_user = user;
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public void MarkUserAsLoggedOut()
{
_user = null;
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
}
在上面的代码中,GetAuthenticationStateAsync 方法通过检查 User 对象来设置身份验证状态。而 MarkUserAsAuthenticated 和 MarkUserAsLoggedOut 方法分别用来处理用户的“登入”和“登出”操作。
要使用这个 CustomAuthenticationStateProvider,您需要在您的 Blazor 组件中注入这个类:
@inject CustomAuthenticationStateProvider CustomAuthenticationStateProvider
@if (context.User.Identity.IsAuthenticated)
{
}
else
{
}
@code {
private async Task Login()
{
var user = new User();
CustomAuthenticationStateProvider.MarkUserAsAuthenticated(user);
}
private async Task Logout()