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

时间:2021-05-26 02:54:53

I'm writing a web application which uses windows authentication and I can happily get the user's login name using something like:

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

 string login = User.Identity.Name.ToString();

But I don't need their login name I want their DisplayName. I've been banging my head for a couple hours now...

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

Can I access my organisation's AD via a web application?

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

5 个解决方案

#1


29  

How about this:

这个怎么样:

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

#2


8  

See related question: Active Directory: Retrieve User information

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

See also: Howto: (Almost) Everything In Active Directory via C# and more specifically section "Enumerate an object's properties".

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

If you have a path to connect to a group in a domain, the following snippet may be helpful:

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

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";
    }
}

#3


4  

Use this:

string displayName = UserPrincipal.Current.DisplayName;

string displayName = UserPrincipal.Current.DisplayName;

#4


3  

In case anyone cares I managed to crack this one:

如果有人关心我设法破解这个:

      /// This is some imaginary code to show you how to use it

      Session["USER"] = User.Identity.Name.ToString();
      Session["LOGIN"] = RemoveDomainPrefix(User.Identity.Name.ToString()); // not a real function :D
      string ldappath = "LDAP://your_ldap_path";
      // "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."


      Session["cn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "cn");
      Session["displayName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "displayName");
      Session["mail"] = GetAttribute(ldappath, (string)Session["LOGIN"], "mail");
      Session["givenName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "givenName");
      Session["sn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "sn");


/// working code

public static string GetAttribute(string ldappath, string sAMAccountName, string attribute)
    {
        string OUT = string.Empty;

        try
        {
            DirectoryEntry de = new DirectoryEntry(ldappath);
            DirectorySearcher ds = new DirectorySearcher(de);
            ds.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + sAMAccountName + "))";

            SearchResultCollection results = ds.FindAll();

            foreach (SearchResult result in results)
            {
                OUT =  GetProperty(result, attribute);
            }
        }
        catch (Exception t)
        {
            // System.Diagnostics.Debug.WriteLine(t.Message);
        }

        return (OUT != null) ? OUT : string.Empty;
    }

public static string GetProperty(SearchResult searchResult, string PropertyName)
    {
        if (searchResult.Properties.Contains(PropertyName))
        {
            return searchResult.Properties[PropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

#5


2  

There is a CodePlex project for Linq to AD, if you're interested.

如果您有兴趣,可以使用Linq到AD的CodePlex项目。

It's also covered in the book LINQ Unleashed for C# by Paul Kimmel - he uses the above project as his starting point.

Paul Kimmel出版的“LINQ Unleashed for C#”一书中也有介绍 - 他以上述项目为出发点。

not affiliated with either source - I just read the book recently

不属于任何一个来源 - 我最近刚读过这本书

#1


29  

How about this:

这个怎么样:

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

#2


8  

See related question: Active Directory: Retrieve User information

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

See also: Howto: (Almost) Everything In Active Directory via C# and more specifically section "Enumerate an object's properties".

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

If you have a path to connect to a group in a domain, the following snippet may be helpful:

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

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";
    }
}

#3


4  

Use this:

string displayName = UserPrincipal.Current.DisplayName;

string displayName = UserPrincipal.Current.DisplayName;

#4


3  

In case anyone cares I managed to crack this one:

如果有人关心我设法破解这个:

      /// This is some imaginary code to show you how to use it

      Session["USER"] = User.Identity.Name.ToString();
      Session["LOGIN"] = RemoveDomainPrefix(User.Identity.Name.ToString()); // not a real function :D
      string ldappath = "LDAP://your_ldap_path";
      // "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."


      Session["cn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "cn");
      Session["displayName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "displayName");
      Session["mail"] = GetAttribute(ldappath, (string)Session["LOGIN"], "mail");
      Session["givenName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "givenName");
      Session["sn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "sn");


/// working code

public static string GetAttribute(string ldappath, string sAMAccountName, string attribute)
    {
        string OUT = string.Empty;

        try
        {
            DirectoryEntry de = new DirectoryEntry(ldappath);
            DirectorySearcher ds = new DirectorySearcher(de);
            ds.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + sAMAccountName + "))";

            SearchResultCollection results = ds.FindAll();

            foreach (SearchResult result in results)
            {
                OUT =  GetProperty(result, attribute);
            }
        }
        catch (Exception t)
        {
            // System.Diagnostics.Debug.WriteLine(t.Message);
        }

        return (OUT != null) ? OUT : string.Empty;
    }

public static string GetProperty(SearchResult searchResult, string PropertyName)
    {
        if (searchResult.Properties.Contains(PropertyName))
        {
            return searchResult.Properties[PropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

#5


2  

There is a CodePlex project for Linq to AD, if you're interested.

如果您有兴趣,可以使用Linq到AD的CodePlex项目。

It's also covered in the book LINQ Unleashed for C# by Paul Kimmel - he uses the above project as his starting point.

Paul Kimmel出版的“LINQ Unleashed for C#”一书中也有介绍 - 他以上述项目为出发点。

not affiliated with either source - I just read the book recently

不属于任何一个来源 - 我最近刚读过这本书