UserPrincipal.Current 从某一天到第二天都会抛出 COMException

Guy*_*tag 5 .net c# active-directory userprincipal

今天早上,我开始注意到我的几个程序在 Active Directory 读取操作方面存在一些问题。我注意到所有这些应用程序(客户端和服务器)都使用System.DirectoryServices.AccountManagement.UserPrincipal该类进行读取操作,而仍然正确运行的程序则使用System.DirectoryServices.DirectorySearcher.

\n

因此,为了缩小问题范围,我构建了以下非常简单的控制台应用程序

\n
class Program\n{\n    static void Main(string[] args)\n    {\n        //this works great\n        Console.WriteLine($"Enviroment.Username:{Environment.UserName}");\n\n        //this works great\n        PrincipalContext pcFull = new PrincipalContext(ContextType.Domain, "my.company.de", "dc=my,dc=company,dc=de");\n        UserPrincipal upPrincipalContextFull = UserPrincipal.FindByIdentity(pcFull, Environment.UserName);\n\n        //this doesn\'t work at all\n        //Exception: \xe2\x80\x9cThe specified directory service attribute or value does not exist\xe2\x80\x9d\n        PrincipalContext pc = new PrincipalContext(ContextType.Domain);\n        UserPrincipal upPrincipalContext = UserPrincipal.FindByIdentity(pc, Environment.UserName);\n\n        //this doesn\'t either, same exception\n        UserPrincipal upCurrent = UserPrincipal.Current;\n        \n        Console.ReadKey();\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

正如您在评论中看到的,后两个操作在我测试的域中的每台计算机上都会失败,即使它们完美运行了几年。UserPrincipal.Current当我调用或未UserPrincipal.FindByIdentity(pc, Environment.UserName);在PrincipalContext中指定Container时,会发生以下异常:

\n

System.Runtime.InteropServices.COMException: \xe2\x80\x9cThe specified directory service attribute or value does not exist\xe2\x80\x9d

\n

这是我所知道的:

\n
    \n
  • 突然停止工作的应用程序在过去两周内都没有收到更新
  • \n
  • 所有这些应用程序、UserPrincipal.Current-Property 和UserPrincipal.FindByIdentity-Method 昨天都运行得很好
  • \n
  • 工作站上周未收到 Windows 或 .Net 更新
  • \n
  • 该现象与单个工作站、用户或操作系统无关,而是在运行 Windows 7 或 10 的许多不同计算机上的许多不同用户中发生。
  • \n
  • 域控制器一周前收到更新。显然,其中一个更新存在有关 LDAP 查询的已知问题:由于 WLDAP32.DLL 中的缺陷,执行 LDAP 引用追踪的应用程序可能会消耗太多动态 TCP 端口。这似乎不太可能是突然失败的原因,因为 a) 该补丁是一周前安装的,问题今天才发生,b) Microsoft 建议的解决方法(重新启动服务)没有任何效果
  • \n
\n

是什么可能导致这种“一夜之间”的行为?如果它确实与 Windows 更新有关,其他用户很快也会遇到这个错误!

\n

显然,我可以构建解决方法,因此我不必使用失败的方法和属性,但我仍然必须知道为什么它首先停止工作。

\n

编辑

\n

首先,了解\npublic PrincipalContext(ContextType contextType);和之间的区别会很有用public PrincipalContext(ContextType contextType, string name, string container);。没有容器构建的PrincipalContext仍然必须以某种方式获取该容器,不是吗?

\n

小智 3

默认情况下,PrincipalContext在“OU=Computers”容器中进行搜索。如果没有为容器设置读取权限,则会失败,并引发 COM 异常。