有没有办法在组件之外访问身份验证状态? 例如,我正在尝试,
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>()
我正在尝试使用当前用户提供程序作为数据库上下文的参数 如
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应该在SetAuthenticationState 之后调用, 我该怎么做???
就个人而言,我倾向于在任何负责首先烹饪实体的业务逻辑中设置实体的任何"创建者"/"创建日期"/等属性。
话虽如此,如果你只是把 AuthenticationStateProvider 放到 ExampleDbContext 构造函数中会发生什么?在调用它时,它不会与 DbContext 一起解析,并允许您找出解析(调用(用户(如果存在(吗?