我的Web应用程序在用户登录时使用Active Directory身份验证。我将以下代码用于审核列。对于CreatedAt和ModifiedAt日期,它工作得很好,但是currentUsername是硬编码的。
public override int SaveChanges()
{
var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseClass && (x.State == EntityState.Added || x.State == EntityState.Modified));
var currentUsername = "T";
foreach (var entity in entities)
{
if (entity.State == EntityState.Added)
{
((BaseClass)entity.Entity).CreatedAt = DateTime.Now;
((BaseClass)entity.Entity).CreatedBy = currentUsername;
}
((BaseClass)entity.Entity).ModifiedAt = DateTime.Now;
((BaseClass)entity.Entity).ModifiedBy = currentUsername;
}
return base.SaveChanges();
}
如何获取当前在Active Directory中登录的用户名?
如果您使用的是.NET 4.5或更高版本,则只需在该上下文中使用System.DirectoryServices.AccountManagement
命名空间和UserPrincipal
类:
// you'll need to add a reference to this .NET assembly in your project
// so that you can use this namespace
using System.DirectoryServices.AccountManagement;
public string GetLoggedInUser()
{
// establish the PrincipalContext - this will grab the default domain, default containers
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// get the currently active user
UserPrincipal currentUser = UserPrincipal.Current;
if (currentUser != null)
{
// this will return "first name last name" separated by a space,
// e.g. "John Doe" or "Jane Tarzan"
return $"{currentUser.GivenName} {currentUser.Surname}";
}
}
return string.Empty;
}