有没有办法在 Component 之外访问身份验证状态?例如我正在尝试,
public class ServersideCurrentUserIdentityProvider : ICurrentUserIdentityProvider, IDisposable
{
private Task<AuthenticationState> currentAuthenticationStateTask;
private readonly AuthenticationStateProvider stateProvider;
public ServersideCurrentUserIdentityProvider(AuthenticationStateProvider stateProvider)
{
this.stateProvider = stateProvider;
stateProvider.AuthenticationStateChanged += OnAuthenticationStateChanged;
currentAuthenticationStateTask = stateProvider.GetAuthenticationStateAsync();
}
private void OnAuthenticationStateChanged(Task<AuthenticationState> task)
{
this.currentAuthenticationStateTask = task;
}
public async Task<ClaimsPrincipal> GetCurrentUserPrincipal()
{
var state = await currentAuthenticationStateTask;
return state.User;
}
public void Dispose()
{
this.stateProvider.AuthenticationStateChanged -= OnAuthenticationStateChanged;
}
}
此类在 DI 中注册为
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
services.AddSingletone<ICurrentUserIdentityProvider,ServersideCurrentUserIdentityProvider>()
我正在尝试使用 CurrentUserProvider 作为 db Context 的参数
public class ExampleDbContext()
{
public ExampleDbContext(DbContextOption opt, ICurrentUserProvider provider){
override Task<int> onSaveChange(){
var principal= await this.userProvider.GetCurrentPrincipal();
foreach ..
entity.CreatedBy=principal.Name;
}
}
当我尝试运行时,我得到异常说,GetAuthenticationState应该在SetAuthentication State 之后调用,我该怎么做???