如何使用 LdapConnection 异步绑定

HCL*_*HCL 5 .net active-directory adlds

虽然通过BeginSendRequest和异步请求执行 LDAP 操作EndSendRequest非常简单,但我无法确定如何异步完成绑定过程。

是否有可能与 SDS.P 的 LdapConnection 异步绑定

Bry*_*n W 3

正在寻找执行异步 LDAP 操作并发现这个未解答的问题。最终我自己弄清楚了:

编辑:这似乎仍然没有 100% 有效。看起来 BeginSendRequest() 在使用此方法查找端点/域控制器/LDAP 服务器时实际上会阻塞。后来当网络配置导致服务器不可用时,才发现这一点。我最终只是使用 Task.Run() 中的同步内容并继续我的生活。

假设您还想在绑定后异步发送/接收 LDAP 请求(不知道为什么您还想绑定),您可以使用 LdapConnection 上的 AutoBind 属性并在构造函数中预先指定凭据以实现“异步绑定” ,通过使用 BeginSendRequest()/EndSendRequest() 并让它以异步方式在内部处理 Bind。

using System.DirectoryServices.Protocols;
using System.Net;
using System.Threading.Tasks;

// ...

using (var connection = 
    new LdapConnection(
        new LdapDirectoryIdentifier("fqdn.example.com", true, false),
        new NetworkCredential("someuser", "somepassword"),
        AuthType.Basic))
{
    // The Answer...
    connection.AutoBind = true;

    var searchResult = await Task.Factory.FromAsync(
            connection.BeginSendRequest, 
            connection.EndSendRequest,
            new SearchRequest(
                "DC=example,DC=com",
                "(objectClass=user)",
                SearchScope.Subtree,
                "distinguishedname"), 
            PartialResultProcessing.NoPartialResultSupport, 
            null);

    // Profit
}
Run Code Online (Sandbox Code Playgroud)

为简洁起见,我将 LdapConnection 上旧的异步编程模型方法 (APM) 放入为基于任务的异步模式 (TAP) 提供的方便的包装方法中,以便在现代 .Net 项目中可以按照预期简单地等待它。请参阅: https: //learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/interop-with-other-asynchronous-patterns-and-types

并没有真正准确地回答问题,但确实表明您实际上不必自己显式绑定,也许这就是为什么 MS 没有费心添加 BeginBind() 等。希望这可以帮助下一个疲倦的程序员与 LDAP 互操作搏斗谁遇到它。