【问题标题】:How to get and filter AD first & last name in ASP.NET如何在 ASP.NET 中获取和过滤 AD 名字和姓氏
【发布时间】:2013-11-07 20:12:04
【问题描述】:
我正在尝试按 AD 用户名搜索并将名字和姓氏显示到表格中。
这是我目前所拥有的:
DirectoryEntry myLDAPConnection = new DirectoryEntry("LDAP://company.com");
DirectorySearcher dSearch = new DirectorySearcher(myLDAPConnection);
我知道我需要对我的 dSearch 对象做一些事情来过滤返回的内容,但我不知道除此之外还能做什么。
【问题讨论】:
标签:
c#
asp.net-mvc
asp.net-mvc-4
active-directory
【解决方案1】:
如果您使用的是 .NET 3.5 及更高版本,则应查看 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。在此处阅读所有相关信息:
基本上,您可以定义域上下文并在 AD 中轻松找到用户和/或组:
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// do something here....
}
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
// if found....
if (group != null)
{
// iterate over members
foreach (Principal p in group.GetMembers())
{
Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
// do whatever you need to do to those members
}
}
}
新的 S.DS.AM 让在 AD 中与用户和组一起玩变得非常容易!