[英]Get current logged in username from Active Directory?
用户登录时,我的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.