Dot-Net

UserPrincipal.GetGroups 失敗,出現未知錯誤

  • December 23, 2010

我正在嘗試使用以下程式碼獲取使用者的所有 Active Directory 組:

   private static IEnumerable<string> GetGroupNames(string userName)
   {
       using (var context = new PrincipalContext(ContextType.Domain))
       {
           using (var userPrincipal = UserPrincipal.FindByIdentity(context, userName))
           {
               var groupSearch = userPrincipal.GetGroups(context);
               var result = new List<string>();
               foreach (var principal in groupSearch)
               {
                   Log.LogDebug("User {0} is member of group {0}", userPrincipal.DisplayName, principal.DisplayName);
                   result.Add(principal.SamAccountName);
               }
               return result;
           }
       }
   }

此程式碼正確找到使用者主體,但在呼叫 GetGroups 並出現 PrincipalOperationException:未知錯誤 (0x80005000) 時失敗。

根異常:

  at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOf(Principal foreignPrincipal, StoreCtx foreignContext)
  at System.DirectoryServices.AccountManagement.Principal.GetGroupsHelper(PrincipalContext contextToQuery)
  at System.DirectoryServices.AccountManagement.Principal.GetGroups(PrincipalContext contextToQuery)
  at [line of the GetGroup call]

內部異常(COMException):

  at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
  at System.DirectoryServices.DirectoryEntry.Bind()
  at System.DirectoryServices.DirectoryEntry.get_AdsObject()
  at System.DirectoryServices.PropertyValueCollection.PopulateList()
  at System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName)
  at System.DirectoryServices.PropertyCollection.get_Item(String propertyName)
  at System.DirectoryServices.AccountManagement.ADUtils.RetriveWkDn(DirectoryEntry deBase, String defaultNamingContext, String serverN

另一個報告有這個問題

有什麼線索嗎?

將 Environment.UserDomainName 作為名稱參數添加到 PrincipalContext 有助於:

using (var context = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))

我仍然不知道為什麼 PrincipalContext(ContextType.Domain) 僅適用於查找 UserPrincipal 而不是使用者組。COM 錯誤消息“未知錯誤”不是很有幫助,只有 ContextType 的 PrincipalContext 建構子重載在 MSDN 中幾乎沒有記錄。正如 Harvey Kwok 所指出的,這聽起來像是 .NET 框架的問題。

引用自:https://stackoverflow.com/questions/4518472