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

如何找到用户';C#web应用程序中的Active Directory显示名称?,c#,active-directory,C#,Active Directory,我正在编写一个使用windows身份验证的web应用程序,我可以很高兴地通过以下方式获得用户的登录名: string login = User.Identity.Name.ToString(); 但我不需要他们的登录名,我需要他们的显示名。我已经撞了我的头好几个小时了 我可以通过web应用程序访问公司的广告吗?请参阅相关问题: 另请参见:更具体地说,请参见第节“” 如果您有连接到域中某个组的路径,以下代码段可能会有所帮助: GetUserProperty("<myaccount>

我正在编写一个使用windows身份验证的web应用程序,我可以很高兴地通过以下方式获得用户的登录名:

 string login = User.Identity.Name.ToString();
但我不需要他们的登录名,我需要他们的显示名。我已经撞了我的头好几个小时了

我可以通过web应用程序访问公司的广告吗?

请参阅相关问题:

另请参见:更具体地说,请参见第节“”

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

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";
    }
}
GetUserProperty(“,“DisplayName”);
公共静态字符串GetUserProperty(字符串accountName、字符串propertyName)
{
DirectoryEntry=新的DirectoryEntry();
//“LDAP://CN=,CN=,DC=,DC=,…”
entry.Path=“LDAP://…”;
entry.AuthenticationType=AuthenticationTypes.Secure;
DirectorySearcher search=新的DirectorySearcher(条目);
search.Filter=“(SAMAccountName=“+accountName+”);
search.PropertiesToLoad.Add(propertyName);
SearchResultCollection results=search.FindAll();
if(results!=null&&results.Count>0)
{
返回结果[0]。属性[propertyName][0]。ToString();
}
其他的
{
返回“未知用户”;
}
}
这个怎么样:

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

如果你有兴趣,这里有一个CodePlex项目

保罗·金梅尔(Paul Kimmel)的书中也提到了这一点——他将上述项目作为自己的出发点


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

,以防有人在意,我设法破解了这本书:

      /// 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;
        }
    }
///这是一些虚构的代码,向您展示如何使用它
会话[“USER”]=USER.Identity.Name.ToString();
会话[“LOGIN”]=RemoveDomainPrefix(User.Identity.Name.ToString());//不是真正的函数:D
string ldappath=“LDAP://your\u LDAP\u path”;
//“LDAP://CN=,CN=,DC=,DC=,…”
会话[“cn”]=GetAttribute(ldappath,(string)会话[“LOGIN”],“cn”);
会话[“displayName”]=GetAttribute(ldappath,(字符串)会话[“登录”],“displayName”);
会话[“邮件”]=GetAttribute(ldappath,(string)会话[“登录”],“邮件”);
会话[“givenName”]=GetAttribute(ldappath,(string)会话[“LOGIN”],“givenName”);
会话[“sn”]=GetAttribute(ldappath,(string)会话[“LOGIN”],“sn”);
///工作代码
公共静态字符串GetAttribute(字符串ldappath、字符串sAMAccountName、字符串属性)
{
string OUT=string.Empty;
尝试
{
DirectoryEntry de=新的DirectoryEntry(ldappath);
DirectorySearcher ds=新的DirectorySearcher(de);
ds.Filter=“(&(objectClass=user)(objectCategory=person)(sAMAccountName=“+sAMAccountName+”)”;
SearchResultCollection results=ds.FindAll();
foreach(搜索结果中的搜索结果)
{
OUT=GetProperty(结果、属性);
}
}
捕获(异常t)
{
//系统.诊断.调试.写线(t.Message);
}
return(OUT!=null)?OUT:string.Empty;
}
公共静态字符串GetProperty(SearchResult SearchResult,string PropertyName)
{
if(searchResult.Properties.Contains(PropertyName))
{
返回searchResult.Properties[PropertyName][0].ToString();
}
其他的
{
返回字符串。空;
}
}
使用以下方法:


string displayName=UserPrincipal.Current.displayName

对于单用户来说,这是最好的方法。是的,我很喜欢这一方法的简单性,尤其是因为它可以工作。我欠你一杯酒!这确实有效,但WINNT://属性的压缩性比LDAP://属性低得多(请参阅),因此,虽然这确实有效,但我无法使用WINNT://绑定获取用户的电子邮件地址。如果您的web应用程序使用Windows身份验证,则此项适用。您需要
System.DirectoryServices.AccountManagement
程序集和命名空间来访问
UserPrincipal