Get distinguished name from Active Directory of cu

2019-07-22 19:56发布

How can I get the distinguished name from Active Directory of the currently logged in user in C#?

2条回答
成全新的幸福
2楼-- · 2019-07-22 20:29

Why wouldn't you just use: System.DirectoryServices.AccountManagement.UserPrincipal.Current.DistinguishedName

查看更多
Evening l夕情丶
3楼-- · 2019-07-22 20:50

Check following snippet. You have pass to Identity.Name from IPrincipal. I assume that the user is already authenticated in Active Directory (ie. using standard IIS authorization methods).

private string GetUserName(string identity)
{
    if (identity.Contains("\\"))
    {
        string[] identityList = identity.Split('\\');
        return identityList[1];
    }
    else
    {
        return identity;
    }
}

public string GetUserDn(string identity)
{            
    var userName = GetUserName(identity);   
    using (var rootEntry = new DirectoryEntry("LDAP://" + adConfiguration.ServerAddress, null, null, AuthenticationTypes.Secure))
    {       
        using (var directorySearcher = new DirectorySearcher(rootEntry, String.Format("(sAMAccountName={0})", userName)))
        {
            var searchResult = directorySearcher.FindOne();                    
            if (searchResult != null)
            {
                using (var userEntry = searchResult.GetDirectoryEntry())
                {
                    return (string)userEntry.Properties["distinguishedName"].Value;                 
                }
            }
        }                
    }   
    return null;
}        
查看更多
登录 后发表回答