我如何获得用户名,我使用ASP.. NET Core MVC和Identity
本文关键字:NET Core MVC Identity ASP 何获得 用户 | 更新日期: 2023-09-27 18:03:12
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();
}
只需注入一个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>
并使用GetUserAsync(HttpContext.User)
ApplicationUser
对象。