如何在C#Web应用程序中找到用户的Active Directory显示名称?

ins*_*ite 22 c# active-directory

我正在编写一个使用Windows身份验证的Web应用程序,我很乐意使用以下内容获取用户的登录名:

 string login = User.Identity.Name.ToString();
Run Code Online (Sandbox Code Playgroud)

但我不需要他们的登录名我想要他们的DisplayName.我现在已经敲了几个小时了...

我可以通过Web应用程序访问我组织的AD吗?

小智 29

这个怎么样:

private static string GetFullName()
    {
        try
        {
            DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName);
            return de.Properties["displayName"].Value.ToString();
        }
        catch { return null; }
    }
Run Code Online (Sandbox Code Playgroud)


Pan*_*nos 8

请参阅相关问题:Active Directory:检索用户信息

另请参阅:Howto :(几乎)通过C#在Active Directory中的所有内容,更具体地说," 枚举对象的属性 "部分.

如果您有路径连接到域中的组,则以下代码段可能会有所帮助:

GetUserProperty("<myaccount>", "DisplayName");

public static string GetUserProperty(string accountName, string propertyName)
{
    DirectoryEntry entry = new DirectoryEntry();
    // "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."
    entry.Path = "LDAP://...";
    entry.AuthenticationType = AuthenticationTypes.Secure;

    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(SAMAccountName=" + accountName + ")";
    search.PropertiesToLoad.Add(propertyName);

    SearchResultCollection results = search.FindAll();
    if (results != null && results.Count > 0)
    {
        return results[0].Properties[propertyName][0].ToString();
    }
    else
    {
            return "Unknown User";
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

用这个:

string displayName = UserPrincipal.Current.DisplayName;