簡體   English   中英

在 ApplicationDbContext 類 (ASP.NET Core) 中訪問經過身份驗證的用戶信息

[英]Accessing Authenticated User Info in ApplicationDbContext class (ASP.NET Core)

我有一個 ApplicationDbContext 類: ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>我在SaveChanges && SaveChangesAsync上覆蓋了方法以包含UpdateAuditEntities方法。 我想要的是獲取登錄用戶的用戶名/電子郵件,以便從 IAuditableEntity 繼承的每個實體都標記為創建/更新實體的用戶。

        private void UpdateAuditEntities()
        {
            var CurrentUserId = ???;
            var modifiedEntries = ChangeTracker.Entries()
                .Where(x => x.Entity is IAuditableEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));


            foreach (var entry in modifiedEntries)
            {
                var entity = (IAuditableEntity)entry.Entity;
                DateTime now = DateTime.UtcNow;

                if (entry.State == EntityState.Added)
                {
                    entity.CreatedDate = now;
                    entity.CreatedBy = CurrentUserId;
                }
                else
                {
                    base.Entry(entity).Property(x => x.CreatedBy).IsModified = false;
                    base.Entry(entity).Property(x => x.CreatedDate).IsModified = false;
                }

                entity.UpdatedDate = now;
                entity.UpdatedBy = CurrentUserId;
            }
        }

做我的研究,我在這里找到了一篇很好的文章但我有一個 DesignTimeDbContextFactory 實現,如下所示:

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            Mapper.Reset();

            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .AddJsonFile("appsettings.Development.json", optional: true)
                .Build();

            var builder = new DbContextOptionsBuilder<ApplicationDbContext>();

            //IUserResolverService userResolverService = ServiceProviderServiceExtensions.CreateScope()

            builder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"], b => b.MigrationsAssembly("SybrinApp.Pro"));

            return new ApplicationDbContext(builder.Options);
        }
    }

建議的解決方案意味着我的 ApplicationDbContext 將需要UserResolverService來實例化。 我如何將UserResolverService注入 DesignTimeDbContextFactory 實現,或者是否有另一種方法可以在我的class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>獲取當前登錄的用戶class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>

好的,已經改變了我的答案。 我從這個url 中借用了來演示你可以做什么。

1) 首先創建一個 DependencyResolver 類來包裝 DI 請注意,我假設您的 userResolveService 正在實現 IUserResolveService

 public class DependencyResolver
{
    public IServiceProvider ServiceProvider { get; }
    public string CurrentDirectory { get; set; }

    public DependencyResolver()
    {
        // Set up Dependency Injection
        IServiceCollection services = new ServiceCollection();
        ConfigureServices(services);
        ServiceProvider = services.BuildServiceProvider();
    }

    private void ConfigureServices(IServiceCollection services)
    {
        // Register any DI you need here
        services.AddTransient<IUserResolverService, UserResolverService>();

    }
}

2) 在您的 DesignTimeDbContextFactory 中,將注釋掉的行替換為:

var resolver = new DependencyResolver();
IUserResolverService svc = resolver.ServiceProvider.GetService(typeof(IUserResolverService))
 as UserResolverService;

然后繼續並根據需要致電

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM