1

有没有办法在 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 之后调用,我该怎么做???

4

1 回答 1

0

就个人而言,我倾向于在任何业务逻辑中首先设置实体的任何“CreatedBy”/“DateCreated”/etc 属性。

话虽如此,如果您只是将 AuthenticationStateProvider 放入 ExampleDbContext 构造函数中会发生什么?调用它时是否会与 DbContext 一起解析它,并允许您找出解析(调用)用户(如果存在)?

于 2020-04-30T00:40:41.497 回答