如何在C#中通过LDAPS连接到Active Directory?

如何在C#中通过LDAPS连接到Active Directory?,c#,active-directory,ldap,C#,Active Directory,Ldap,在该站点的应答线程中找到文档(),但我无法连接到广告。当我使用类似Active Directory Explorer的程序时,我可以连接。我想,因为我正在尝试连接到LDAPS,所以我需要一种不同的方法 我有服务器IP、域、用户名/pwd和端口636。 我尝试了各种组合@new DirectoryEntry,但无法将其连接。始终获取一个COMException域不存在 static DirectoryEntry createDirectoryEntry() { Di

在该站点的应答线程中找到文档(),但我无法连接到广告。当我使用类似Active Directory Explorer的程序时,我可以连接。我想,因为我正在尝试连接到LDAPS,所以我需要一种不同的方法

我有服务器IP、域、用户名/pwd和端口636。 我尝试了各种组合@
new DirectoryEntry
,但无法将其连接。始终获取一个
COMException域不存在

    static DirectoryEntry createDirectoryEntry()
    {
        DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://192.168.2.59", USER, PWD);

        ldapConnection.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;

        return ldapConnection;
    }            

背景资料: 用户将其卡放入读卡器单元。Porgram从卡中获取ID,并在DB中搜索该ID,并返回属于该ID/用户的电子邮件地址 . 这里是工作解决方案:

        private string getEmail(string userID)
    {
        try
        {
            string ldapfilter = "(&(otherPager=" + userID + "))";

            DirectoryEntry myLdapConnection = new DirectoryEntry("LDAP://" + SERVER, USER, PWD);
            DirectorySearcher search = new DirectorySearcher(myLdapConnection);
            search.Filter = ldapfilter;

            /*search.PropertiesToLoad.Add("mail");
            SearchResult result = search.FindOne();*/

            string[] requiredValue = new String[] { "mail" };

            foreach (String value in requiredValue)
                search.PropertiesToLoad.Add(value);

            SearchResult result = search.FindOne();

            if (result != null)
            {
                foreach (String value in requiredValue)
                    foreach (Object myCollection in result.Properties[value])
                    {
                       return myCollection.ToString();
                    }    
            }
            else
            {
                return "No Entry fround";
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception Problem: " + e.ToString());
            return null;
        }
        return null;
    }



    private void cmdClose_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        label1.Text = getEmail(textBox1.Text);
    }

您需要指定端口,因为636是默认的LDAPS端口

new DirectoryEntry("LDAP://192.168.2.59:636", USER, PWD)
我在一些代码中这样做,使用“LDAP://”(而不是“LDAPS://”)才有效

如果这不起作用,则可能存在证书错误。您可以使用浏览器对此进行测试。如果您使用Chrome,请使用此选项打开Chrome(以便使用端口636):


那就去。如果您得到一个很大的证书错误,那么问题是证书不可信。查看来自Chrome的证书并查看问题所在。它可能是由不在Windows证书存储中的机构颁发的。

请尝试类似“LDAPS://:636/DC=example,DC=com”的方式。thx非常成功地使它发挥了作用。我更新了上面的代码,让其他人也有同样的问题。也许你/某人可以看看它,并给我反馈如何改进代码/性能等。?“我在一些代码中这样做了,使用“LDAP://”(而不是“LDAPS://”)才有效。”这对我来说很有效-不要使用
LDAPS://
。在我的C#apps中,案例似乎也很重要。在我的java应用程序中,我更改了
ldap://...:389
ldaps://...:636
没有问题。
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --explicitly-allowed-ports=636