登录时从Active Directory检索用户信息
本文关键字:检索 用户 信息 Directory Active 登录 | 更新日期: 2023-09-27 17:54:34
我建立了一个网页ASP。Net需要登录活动目录。登录成功。但是如何从AD中检索当前用户信息,如全名并显示在我的主页上。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();
}
}
下面的代码将从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;
}
}