entity-framework-core - 如何在存储库模式 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();
}
任何专家的建议将不胜感激。
解决方案
您可以像下面这样获取当前用户 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...
}
}
推荐阅读
- android - 为什么android.Matrix.setRotateM返回一个旋转方向与预期旋转矩阵相反的矩阵?
- sql - SELECT 查询错误 ORA-01722(无效数字)
- javascript - 我想做 MouseMove 事件,但它不起作用
- r - 如何绘制季节性图?
- swift - 为什么使用 24 小时制的设备会出现以下时间排序代码中断?
- node.js - MongoDB Atlas 错误:无效架构,预期 mongodb
- javascript - Traversy 的可过滤列表
- sql - 如何将数据从一个数据库复制到具有实时 IP 的两台不同机器上的另一个数据库?
- hibernate - 如果@ManyToOne双向的jpa中的子表复合键中存在外键,如何停止在父表中插入?
- node.js - 在nodejs中下载图像并调整大小