我正在尝试开发一个类库,我希望在其中实现自定义DbContext
。在SaveChanges
的{{1}}方法中,我需要获取当前用户的信息(部门,用户名等)以供审核。 DbContext
代码的某些部分位于以下位置:
DbContext
有两种选择:
public override int SaveChanges()
{
// find all changed entities which is ICreateAuditedEntity
var addedAuditedEntities = ChangeTracker.Entries<ICreateAuditedEntity>()
.Where(p => p.State == EntityState.Added)
.Select(p => p.Entity);
var now = DateTime.Now;
foreach (var added in addedAuditedEntities)
{
added.CreatedAt = now;
added.CreatedBy = ?;
added.CreatedByDepartment = ?
}
return base.SaveChanges();
}
保存用户信息,注入IHttpContextAccessor并从中获取信息
HttpContext.Items
(在这种情况下,HttpContext.Items
取决于DbContext
,是吗?
正确的吗?)HttpContext
并从对象获取信息(我阅读了一些帖子
那个ThreadStatic不安全)问题:哪种情况最适合我的情况?你有其他建议吗?
答案 0 :(得分:29)
我实现了类似于this blog post中涵盖的方法,并且基本上涉及创建一个服务,该服务将使用依赖注入将HttpContext
(和底层用户信息)注入特定上下文,或者但你更愿意使用它。
一个非常基本的实现可能如下所示:
public class UserResolverService
{
private readonly IHttpContextAccessor _context;
public UserResolverService(IHttpContextAccessor context)
{
_context = context;
}
public string GetUser()
{
return _context.HttpContext.User?.Identity?.Name;
}
}
您只需要在ConfigureServices
文件的Startup.cs
方法中将其注入管道:
services.AddTransient<UserResolverService>();
最后,只需在指定的DbContext
:
public partial class ExampleContext : IExampleContext
{
private YourContext _context;
private string _user;
public ExampleContext(YourContext context, UserResolverService userService)
{
_context = context;
_user = userService.GetUser();
}
}
然后,您应该可以使用_user
来引用上下文中的当前用户。这可以很容易地扩展到存储/访问当前请求中可用的任何内容。
答案 1 :(得分:0)
感谢@RionWilliams提供原始答案。这是我们通过DbContext
3.1中的AD B2C
,.Net Core
用户和Web Api解决CreatedBy和UpdatedBy的方式。 SysStartTime
和SysEndTime
基本上是CreatedDate
和UpdatedDate
,但通过时态表具有版本历史记录(有关在任何时间点存储在表中的数据的信息)。
有关此内容的更多信息:
https://stackoverflow.com/a/64776658/3850405
通用接口:
public interface IEntity
{
public DateTime SysStartTime { get; set; }
public DateTime SysEndTime { get; set; }
public int CreatedById { get; set; }
public User CreatedBy { get; set; }
public int UpdatedById { get; set; }
public User UpdatedBy { get; set; }
}
DbContext:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(
DbContextOptions options) : base(options)
{
}
public DbSet<User> User { get; set; }
public string _currentUserExternalId;
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var user = await User.SingleAsync(x => x.ExternalId == _currentUserExternalId);
AddCreatedByOrUpdatedBy(user);
return (await base.SaveChangesAsync(true, cancellationToken));
}
public override int SaveChanges()
{
var user = User.Single(x => x.ExternalId == _currentUserExternalId);
AddCreatedByOrUpdatedBy(user);
return base.SaveChanges();
}
public void AddCreatedByOrUpdatedBy(User user)
{
foreach (var changedEntity in ChangeTracker.Entries())
{
if (changedEntity.Entity is IEntity entity)
{
switch (changedEntity.State)
{
case EntityState.Added:
entity.CreatedBy = user;
entity.UpdatedBy = user;
break;
case EntityState.Modified:
Entry(entity).Reference(x => x.CreatedBy).IsModified = false;
entity.UpdatedBy = user;
break;
}
}
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var property in modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(string)))
{
if (property.GetMaxLength() == null)
property.SetMaxLength(256);
}
foreach (var property in modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(DateTime)))
{
property.SetColumnType("datetime2(0)");
}
foreach (var et in modelBuilder.Model.GetEntityTypes())
{
foreach (var prop in et.GetProperties())
{
if (prop.Name == "SysStartTime" || prop.Name == "SysEndTime")
{
prop.ValueGenerated = Microsoft.EntityFrameworkCore.Metadata.ValueGenerated.OnAddOrUpdate;
}
}
}
modelBuilder.Entity<Question>()
.HasOne(q => q.UpdatedBy)
.WithMany()
.OnDelete(DeleteBehavior.Restrict);
}
ExtendedApplicationDbContext:
public class ExtendedApplicationDbContext
{
public ApplicationDbContext _context;
public UserResolverService _userService;
public ExtendedApplicationDbContext(ApplicationDbContext context, UserResolverService userService)
{
_context = context;
_userService = userService;
_context._currentUserExternalId = _userService.GetNameIdentifier();
}
}
UserResolverService:
public class UserResolverService
{
public readonly IHttpContextAccessor _context;
public UserResolverService(IHttpContextAccessor context)
{
_context = context;
}
public string GetGivenName()
{
return _context.HttpContext.User.FindFirst(ClaimTypes.GivenName).Value;
}
public string GetSurname()
{
return _context.HttpContext.User.FindFirst(ClaimTypes.Surname).Value;
}
public string GetNameIdentifier()
{
return _context.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
}
public string GetEmails()
{
return _context.HttpContext.User.FindFirst("emails").Value;
}
}
启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddTransient<UserResolverService>();
services.AddTransient<ExtendedApplicationDbContext>();
...
然后可以在任何Controller
中这样使用:
public class QuestionsController : ControllerBase
{
private readonly ILogger<QuestionsController> _logger;
private readonly ExtendedApplicationDbContext _extendedApplicationDbContext;
public QuestionsController(ILogger<QuestionsController> logger, ExtendedApplicationDbContext extendedApplicationDbContext)
{
_logger = logger;
_extendedApplicationDbContext = extendedApplicationDbContext;
}