我正在尝试从LDAP服务器的Active Directory中获取特定组的所有用户。身份验证成功但我的结果为空。 以下是我的代码。
域的172.11.12.123
Email-sample@email.com
密码-123456
using (var context = new DirectoryEntry(user.Domain, user.Email, user.Password, AuthenticationTypes.Secure))
{
try
{
string FirstName;
string LastName;
string ADUserName;
string Email;
using (var searcher = new DirectorySearcher(context))
{
searcher.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname='user3'))";
List<string> Adusers = new List<string>();
System.DirectoryServices.SearchResult result = searcher.FindOne();
}
}
catch (Exception ex)
{
TempData["message"] = "error";
return RedirectToAction("Index", "ADuserList");
}
}
发生了什么问题。 提前致谢
答案 0 :(得分:0)
如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。
基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:
// set up domain context for the currently connected AD domain
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// 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中的用户和群组一起玩!
在这里阅读更多相关信息:
更新:为了获得给定OU的所有用户,方法完全不同。
您需要创建一个单独的PrincipalContext
来定义您感兴趣的OU - 然后您需要使用PrincipalSearcher
来获取该OU中的所有用户:
// create your domain context and define what OU to use:
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, "OU=YourOU,OU=SubOU,dc=YourCompany,dc=com"))
{
// define a "query-by-example" principal - here, we search for any UserPrincipal
UserPrincipal qbeUser = new UserPrincipal(ctx);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
}