如何在建立上下文时设置连接超时 - PrincipalContext

Sta*_*ace 6 c# directoryservices adsi c#-4.0 principalcontext

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Domain, UserName, Password))
            {
                UserPrincipal U = new UserPrincipal(ctx);
                U.GivenName = strFirstName;
                U.Surname = strLastName;
                U.EmailAddress = strEmail;

                PrincipalSearcher srch = new PrincipalSearcher(U);

                foreach (var principal in srch.FindAll())
                {
                    var p = (UserPrincipal)principal;
                    if (!User.Any(x => x.Email == p.EmailAddress))
                    {
                        MyUserDataset.UserRow User = User.NewUserRow();
                        User.FirstName = p.GivenName;
                        User.LastName = p.Surname;
                        User.UserName = p.SamAccountName;
                        User.Email = p.EmailAddress;
                        User.AddUserRow(User);
                    }
                }
                User.AcceptChanges();
            }
Run Code Online (Sandbox Code Playgroud)

我正在使用上面的PrincipalContext类来建立与目标目录的连接,并指定用于对目录执行操作的凭据.

有没有人知道如何在PrincipalContext构造函数中指定连接超时?我遇到连接超时问题我想知道我是否可以控制连接超时多长时间.

big*_*zhu 2

嗯,不幸的是,我想答案是否定的。我深入研究了PrincipalContext的源代码,它使用DirectoryEntry,它使用不安全的本机方法System.DirectoryServices.Interop.UnsafeNativeMethods.ADsOpenObject来打开LDAP连接。

根据此博客How to specify TimeOut for ldap bind in .Net,无法在 ADsOpenObject 上配置超时。不过,它也提到,如果直接使用LdapConnection,那么可以设置超时。在这种情况下,您可能无法使用PrincipalContext。