首页 > 解决方案 > 如何在存储库模式 IdentityDBContext 类中登录 UserID 以覆盖 SaveChanges() 方法?

问题描述

我正在开发 .Net Core 5.0 Web 应用程序,并使用存储库模式和工作单元模式进行数据库操作。

我正在通过 .Net Core Web API 项目访问和使用存储库模式的接口(代码),该项目与另一个 Asp.Net Core 5.0 Web 项目(客户端)进行通信。我已经在 Asp.Net Core 5.0 Web 和 Web API 项目上实现了 Asp.Net Core Identity。我可以在客户端对用户进行身份验证和授权,并在 Web API 项目上创建了 JWT Token 用于用户身份验证。

我想做的是保留每个数据库实体的历史信息,并添加了用于历史目的的字段,如 CreatedBy、UpdateBy、CreatedDate、UpdatedDate 和 IsActive。目前,没有为这些字段添加记录。

我在网上进行了研究,并有了一个覆盖类SaveChanges()方法的想法,IdentityDBContext并尝试了一些示例,但我无法在存储库模式中获取当前登录的 userId(登录客户端项目的用户),所以我可以将它用于 CreatedBy 和 UpdatedBy 字段。

我曾尝试使用索赔原则编写自定义服务,但这些都不能帮助我解决我的问题。

IdentityDBContext在存储库项目中有我的类(这个类库项目作为参考添加到我的 API 和客户端项目中)。

这是我SaveChanges()IdentityDBContext课堂上的方法:

public override int SaveChanges()
        {
            var selectedEntityList = ChangeTracker.Entries()
                                    .Where(x => x.Entity is BaseEntity &&
                                    (x.State == EntityState.Added || x.State == EntityState.Modified));

            var userId = _user;

            foreach (var entity in selectedEntityList)
            {

                ((BaseEntity)entity.Entity).CreatedDate = DateTime.Now;
                ((BaseEntity)entity.Entity).UpdatedDate = DateTime.Now;
                ((BaseEntity)entity.Entity).CreatedBy = "";
                ((BaseEntity)entity.Entity).UpdatedBy = "";
            }

            return base.SaveChanges();
        }

任何专家的建议将不胜感激。

标签: entity-framework-coreasp.net-core-webapirepository-patternasp.net-core-5.0savechanges

解决方案


您可以像下面这样获取当前用户 ID:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public override int SaveChanges()
    {
        var httpContextAccessor = this.GetService<IHttpContextAccessor>();
        var userId = httpContextAccessor.HttpContext?.User
                               .FindFirst(ClaimTypes.NameIdentifier).Value;

        //do your stuff...
    }
}

推荐阅读