有什么方法可以访问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作为数据库上下文的参数
public class ExampleDbContext()
{
public ExampleDbContext(DbContextOption opt, ICurrentUserProvider provider){
override Task<int> onSaveChange(){
var principal= await this.userProvider.GetCurrentPrincipal();
foreach ..
entity.CreatedBy=principal.Name;
}
}
当我尝试运行时,我得到 exception ,说 GetAuthenticationState 应该在 SetAuthentication 状态, 我该怎么做???
答案 0 :(得分:0)
我个人倾向于设置任何实体负责的实体的“ CreatedBy” /“ DateCreated” / etc属性。
话虽如此,如果仅将AuthenticationStateProvider放入ExampleDbContext构造函数中会怎样?调用它时,它是否会与DbContext一起解析,并允许您找出解析(调用)用户(如果存在的话)?