如何使用LdapConnection 类链接 Ldap服务器

2025-03-23 11:05:20
推荐回答(1个)
回答1:

您好,很高兴为您解答。

1 static LdapConnectionldapConnection; 2 static string ldapServer; 3 static NetworkCreden

  
C#提供了 LdapConnection 类用于连接Microsoft Active Directory 域服务或 LDAP 服务器的 TCP/IP 或 UDP LDAP 连接。
下面是连接 Ldap的连接方法和大家分享下:

static LdapConnection ldapConnection;
static string ldapServer;
static NetworkCredential credential;
static string targetOU;
static string pwd;
public void LdapBind()
{
ldapServer = "172.18.69.204:389";
targetOU = "cn=Manager,dc=tst,dc=com";
pwd = "000000";
//credential = new NetworkCredential(String.Empty, String.Empty);
credential = new NetworkCredential(targetOU, pwd);
string dn = "";
//ldapConnection = new LdapConnection(new LdapDirectoryIdentifier(ldapServer));
//ldapConnection.SessionOptions.ProtocolVersion = 3;//Ldap协议版本
//ldapConnection.AuthType = AuthType.Anonymous;//不传递密码进行连接
ldapConnection = new LdapConnection(ldapServer);
ldapConnection.AuthType = AuthType.Basic;
ldapConnection.Credential = credential;
try
{
Console.WriteLine("链接.");
ldapConnection.Bind();
Console.WriteLine("链接成功");
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
}
ldapConnection.Dispose();

}

注意

如果我们使用ldapConnection.AuthType = AuthType.Anonymous; 的认证方式,就一定要让Dn与Pwd为空,实现匿名认证方式,如:

1

credential = new NetworkCredential(String.Empty, String.Empty);

如若满意,请点击右侧【采纳答案】,如若还有问题,请点击【追问】

希望我的回答对您有所帮助,望采纳!