首页 文章

连接到LDAP服务器会抛出NullReferenceException

提问于
浏览
0

我正在尝试使用 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 回答

  • 2

    如上所述here,问题可能是您尝试使用不支持此OpenLDAP的类 PrincipalContext 连接到 Apache Directory Studio

    所以一种方法是使用 DirectoryEntry

  • 1

    使用 DirectoryEntry 它对我有用,如下所示:

    using (var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://ldap.forumsys.com:389/dc=example,dc=com", "", "", AuthenticationTypes.None)))
    {
        searcher.Filter = "((objectClass=person))";
        searcher.PropertiesToLoad.Add("mail");//email
        searcher.PropertiesToLoad.Add("givenName");//first name
        searcher.PropertiesToLoad.Add("sn"); //last name
        searcher.PropertiesToLoad.Add("telephoneNumber");
        searcher.PropertiesToLoad.Add("description");
        searcher.PropertiesToLoad.Add("memberOf"); // groups
    
        var activeDirectoryStaffs = searcher.FindAll();
        if (activeDirectoryStaffs != null)
        {
            for (int i = 0; i < activeDirectoryStaffs.Count; i++)
            {
                SearchResult result = activeDirectoryStaffs[i];
                var Email = result.Properties.Contains("mail") ? (string)result.Properties["mail"][0]:null;
                var Mobile = result.Properties.Contains("telephoneNumber") ? (string)result.Properties["telephoneNumber"][0] : null;
                var FirstName = result.Properties.Contains("givenName") ? (string)result.Properties["givenName"][0] : null;
                var LastName = result.Properties.Contains("sn") ? (string)result.Properties["sn"][0] : null;
                var Description = result.Properties.Contains("description") ? (string)result.Properties["description"][0] : null;
    
            }
        }
    }
    

相关问题