0

不知道为什么会发生这种情况,但是当我运行此代码时,它可以在一台服务器上运行,但不能在另一台服务器上运行。

两台服务器都返回正确的 found.DisplayName,但是只有一台服务器返回 oUserPrincipal 的值,而另一台服务器返回空值。

错误行:

       UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.DisplayName) returns null


        dynamic config = _getExpandoFromXml("config.xml");

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, config.activeDirectory.sDomain, config.activeDirectory.sDefaultOU,config.mailServer.user, config.mailServer.pass);
        UserPrincipal user = new UserPrincipal(ctx);

        PrincipalSearcher search = new PrincipalSearcher(user);
        Console.WriteLine("before foreach");
        foreach (Principal found in search.FindAll())
        {
            try{
                if (found.DisplayName == null)
                {
                    Console.WriteLine("found.Dispalyname is null");
                }
                else
                {    
                    Console.Write("Dispalyname: ");
                    Console.WriteLine(found.DisplayName);
                }
                UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.DisplayName);
                Console.Write("looking for user: ");
                Console.WriteLine(found.DisplayName);
                Console.WriteLine("after findbyidentiy");
                if (oUserPrincipal == null)
                {
                    Console.WriteLine("oUserPrinciapal is null");
                }
                if (oUserPrincipal.LastPasswordSet == null)
                {
                    Console.WriteLine("lastpasswordset is null");
                }
                DateTime? dateOrNull = oUserPrincipal.LastPasswordSet;
                Console.WriteLine("after LastPasswordSet");
4

2 回答 2

1

FindByIdentity 只能搜索少数几个属性。这些是“ IdentityType枚举中包含的任何格式”。

Name 是一个有效选项,但 DisplayName 未列出,因此您可能会得到 DisplayName 和 Name 恰好相同的结果,否则它将失败。

使用:

var oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.Name);

或者

var oUserPrincipal = UserPrincipal.FindByIdentity(ctx, found.SamAccountName);

应该管用。

FindByIdentity还有一个三参数版本,可让您指定要搜索的属性。

于 2013-03-13T22:19:50.977 回答
0

就我而言,我发现问题在于它没有连接到 AD 服务器。如果我将鼠标悬停在 上oPrincipalContext,它的属性ConnectedServer表明它抛出了一个类型异常System.DirectoryServices.DirectoryServicesCOMException。如果发生这种情况,应该重新启动域控制器上的服务。我们发现它可能发生在高登录时间,因为我们的开发网络上只有 1 个 DC。

在此处输入图像描述

于 2016-11-09T18:23:39.880 回答