[英]Search LastName and FirstName in AD
I want to retrieve the first name and last name of the user that is logged in his/her machine using AD. 我想检索使用AD登录到他/她的计算机中的用户的名字和姓氏。 I use the following code: 我使用以下代码:
string server = ConfigurationManager.AppSettings["ActiveDirectory.Server"];
DirectoryEntry entry = new DirectoryEntry(@"LDAP://" + server);
DirectorySearcher searcher = new DirectorySearcher(entry);
User user = GetUser(entry);
searcher.Filter = "sAMAccountName=" + user.UserAD;
searcher.PropertiesToLoad.Add("memberof");
SearchResult result = searcher.FindOne();
private static User GetUser(DirectoryEntry userEntry)
{
Usuario user = new User();
string[] username = HttpContext.Current.Request.ServerVariables["AUTH_USER"].Split('\\');
//THIS IS WHAT I NEED BUT IT DOES RETURN null.
//User.Name= (string)userEntry.Properties["givenName"].Value;
//User.LastName= (string)userEntry.Properties["sn"].Value;
user.Domain = username[0];
user.UserAD = username[1];
return user;
}
Now, I know searcher.PropertiesToLoad
have a [memberof]
and [adspath]
, the last one gives me the first and last name separated with a comma, something like CN="gates, billy"
but I dont want to use substrings and index, is there any property like [firstName]
, [lastName]
in the list properties? 现在,我知道searcher.PropertiesToLoad
具有[memberof]
和[adspath]
,最后一个给我的名字和姓氏用逗号分隔,类似于CN="gates, billy"
但是我不想使用子字符串和索引,列表属性中是否有[firstName]
, [lastName]
之类的属性?
I did search that DirectoryEntry
have a property called givenName
and sn
but this returns null
我确实搜索了DirectoryEntry
具有名为givenName
和sn
的属性,但这返回null
The PropertiesToLoad
set is exactly what you need to modify. PropertiesToLoad
设置正是您需要修改的。 Active Directory will return only the properties which are defined in this set, that's why you don't see givenName
and sn
. Active Directory将仅返回此集中定义的属性,这就是为什么看不到givenName
和sn
。 Just add these properties as well: 只需添加以下属性:
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("sn");
Alternatively, just add the property *
to load all of them: 另外,只需添加属性*
即可加载所有属性:
searcher.PropertiesToLoad.Add("*");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.