从Active Directory获取当前登录的用户名吗?

问题描述 投票:1回答:1

我的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中登录的用户名?

asp.net authentication web-applications active-directory audit
1个回答
0
投票

如果您使用的是.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;  
} 
© www.soinside.com 2019 - 2024. All rights reserved.