我如何获得用户名,我使用 ASP.NET 核心 MVC 和身份?

How I get the UserName, I use ASP.NET Core MVC and Identity?

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 注入到您的 class 中(作为构造函数依赖项),然后您就可以从上下文中的 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)