登录时从Active Directory检索用户信息

时间:2015-06-09 02:19:57

标签: c# login active-directory

我构建了一个使用Active Directory登录所需的ASP.Net页面。登录成功。但如何从AD中检索当前用户信息,如全名,并在我的mainpage.aspx(C#)中显示

我在我的代码上尝试了这个

using System.DirectoryServices;
   using (DirectoryEntry de = new DirectoryEntry("LDAP://SUTRA"))
        {
            using (DirectorySearcher adSearch = new DirectorySearcher(de))
            {
                string username = HttpContext.Current.Request.ServerVariables["AUTH_USER"];
                adSearch.Filter = "(sAMAccountName=someuser)";
                SearchResult adSearchResult = adSearch.FindOne();
            }
        }

1 个答案:

答案 0 :(得分:0)

以下代码将返回用户的AD中的FirstName和LastName

  public string GetUserDetails(string UserID)
    {
        try
        {
            DirectorySearcher search = default(DirectorySearcher);
            DirectoryEntry entry = default(DirectoryEntry);
            SearchResult sr = default(SearchResult);
            System.DirectoryServices.PropertyCollection propertycol = default(System.DirectoryServices.PropertyCollection);
            entry = new DirectoryEntry("LDAP://DomainName.com");
            propertycol = entry.Properties;
            search = new DirectorySearcher(entry);
            search.Filter = "(sAMAccountName=" + UserID + ")";                
            sr = search.FindOne();
            string fname = "";
            string lname = "";

            if ((sr != null))
            {
                if (sr.Properties.Count > 1)
                {
                    fname = Convert.ToString(sr.GetDirectoryEntry().Properties["givenName"].Value);

                    lname = Convert.ToString(sr.GetDirectoryEntry().Properties["sn"].Value);
                }
                return fname + "\n" + lname ;
            }

          return "User Id not found";
        }
        catch (Exception ex)
        {
            return "Error:" + ex.Message;
        }
    }