public override int SaveChanges()
{
var modifiedEntries = ChangeTracker.Entries().Where(x => x.Entity is IAuditableEntity && x.State == EntityState.Added || x.State == EntityState.Modified);
ApplicationUser userLogIn = new ApplicationUser();
foreach (var entry in modifiedEntries)
{
if(entry != null)
{
var entity = entry.Entity as IAuditableEntity;
//in MVC5 i use HttpContext.Current.User.Identity.Name//In MVC6 I don't know to do
var user = "User";
var now = DateTime.Now;
if (entry.State == EntityState.Added)
{
entity.CreatedBy = user;
entity.CreatedOn = now;
entity.IsDeleted = false;
}
else
{
base.Entry(entity).Property(x => x.CreatedBy).IsModified = false;
base.Entry(entity).Property(x => x.CreatedOn).IsModified = false;
base.Entry(entity).Property(x => x.IsDeleted).IsModified = false;
}
entity.UpdatedBy = user;
entity.UpdatedOn = now;
}
}
return base.SaveChanges();
}
问问题
616 次
1 回答
0
只需将一个注入IHttpContextAccessor
到您的类中(作为构造函数依赖项),然后您就可以从User
上下文中的对象获取名称:
private IHttpContextAccessor context;
public SomeRepo(IHttpContextAccessor context)
{
this.context = context;
}
//in your method
var userName = this.context.HttpContext.User.Identity.Name;
由于您使用的是身份框架,如果您需要当前用户的其他数据而不是其名称,您可以使用其任何方法注入UserManager<ApplicationUser>
和检索整个ApplicationUser
对象,例如GetUserAsync(HttpContext.User)
于 2016-08-20T11:28:58.907 回答