我正在尝试使用 System.DirectoryServices.AccountManagement
连接到指定here的在线测试LDAP服务器,如下所示:
try
{
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "ldap.forumsys.com:389", "dc=example,dc=com", "cn=read-only-admin,dc=example,dc=com", "password"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(ctx )))
{
foreach (var result in searcher.FindAll().Take(usersCount))
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
}
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
但它抛出以下异常:
对象引用未设置为对象的实例 .
您能否告诉我的代码有什么问题以及如何连接到该LDAP服务器?
PS:我可以使用Apache Directory Studio连接到该服务器
堆栈跟踪 :
在在System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval()在System.DirectoryServices.AccountManagement.PrincipalContext..ctor System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(字符串服务器名,ServerProperties&性质)(ContextType contextType,字符串名,字符串容器,ContextOptions选项,用户名字符串,字符串密码)在System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType,字符串名,字符串容器,字符串用户名,字符串密码)在ConsoleApp1.Program.GetGroups(用户名字符串)在C: \ Users \ Simple Code \ source \ repos \ ConsoleApp1 \ ConsoleApp1 \ Program.cs:第48行
2 回答
如上所述here,问题可能是您尝试使用不支持此OpenLDAP的类
PrincipalContext
连接到 Apache Directory Studio ,所以一种方法是使用
DirectoryEntry
类使用 DirectoryEntry 它对我有用,如下所示: