Guy*_*tag 5 .net c# active-directory userprincipal
今天早上,我开始注意到我的几个程序在 Active Directory 读取操作方面存在一些问题。我注意到所有这些应用程序(客户端和服务器)都使用System.DirectoryServices.AccountManagement.UserPrincipal该类进行读取操作,而仍然正确运行的程序则使用System.DirectoryServices.DirectorySearcher.
因此,为了缩小问题范围,我构建了以下非常简单的控制台应用程序
\nclass 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}\nRun Code Online (Sandbox Code Playgroud)\n正如您在评论中看到的,后两个操作在我测试的域中的每台计算机上都会失败,即使它们完美运行了几年。UserPrincipal.Current当我调用或未UserPrincipal.FindByIdentity(pc, Environment.UserName);在PrincipalContext中指定Container时,会发生以下异常:
System.Runtime.InteropServices.COMException: \xe2\x80\x9cThe specified directory service attribute or value does not exist\xe2\x80\x9d
这是我所知道的:
\nUserPrincipal.Current-Property 和UserPrincipal.FindByIdentity-Method 昨天都运行得很好是什么可能导致这种“一夜之间”的行为?如果它确实与 Windows 更新有关,其他用户很快也会遇到这个错误!
\n显然,我可以构建解决方法,因此我不必使用失败的方法和属性,但我仍然必须知道为什么它首先停止工作。
\n首先,了解\npublic PrincipalContext(ContextType contextType);和之间的区别会很有用public PrincipalContext(ContextType contextType, string name, string container);。没有容器构建的PrincipalContext仍然必须以某种方式获取该容器,不是吗?