2014-11-25 81 views
0
public bool IsUserGroupMember(string user, string unit) 
{ 
    bool member = false; 

    try 
    { 
     PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 
     string[] groups = unit.Split(','); 
     foreach (string word in groups) 
     { 
      GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, word); 

      if (grp != null) 
      { 
       foreach (Principal p in grp.GetMembers(true)) 
       { 
        if (p.SamAccountName == user) 
        { 
         member = true; 
         grp.Dispose(); 
         ctx.Dispose(); 
         return member; 
        } 
       } 
      } 
      else 
      { 
       grp.Dispose(); 
       ctx.Dispose(); 
       return member; 
      } 
     } 
    } 
    catch (COMException) 
    { 
     return member; 
    } 

    return member; 
} 

我正在使用上面的方法,以遞歸方式查找用戶是否是Active Directory中組的成員。它運作良好。儘管有時我會遇到一個奇怪的例外。Active Directory異常asp .net

不支持指定的方法。 foreach(grp.GetMembers(true)中的Principal p)是紅色的(抱歉,我無法上傳該例外的圖片)。最奇怪的是,它似乎是隨機拋出,如果我刷新頁面效果很好..

我試着在網上找,但現在沒有好消息就解決..

回答

0

我終於結束瞭解決方案!

我剛加入我的域名,如下:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "MyDomain"); 

它解決了這個問題的時候了!

關於緩慢..我使用餅乾,繼此link

0

你應該以相反的方式做到這一點:獲得用戶,然後是該用戶所屬的授權組 - 此調用(.GetAuthorizationGroupsUserPrincipal已經是爲您遞歸搜索組!

public bool IsUserGroupMember(string user, string unit) 
{ 
    bool isMember = false; 

    try 
    { 
     // put the PrincipalContext in a using(..) block - then it's 
     // automatically, safely and properly disposed of at the end 
     using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) 
     { 
      // get the user 
      UserPrincipal up = UserPrincipal.FindByIdentity(ctx, user); 

      if(up != null) 
      { 
       // get the authorization groups for the user 
       // this call is *RECURSIVELY* enumerating all groups 
       // that this user is a member of 
       var authGroups = up.GetAuthorizationGroups(); 

       // now that you have the groups - just determine if the user 
       // is a member of the group you're looking for...... 
      } 
     } 
    } 
    catch (COMException comEx) 
    { 
     isMember = false; 
    } 

    return isMember; 
} 
+0

謝謝你的回覆@marc_s。我瞭解你的代碼。現在唯一的問題是我得到這個exeption:'up.GetAuthorizationGroups()'拋出了類型'System.AppDomainUnloadedException'的異常System.DirectoryServices.AccountManagement.PrincipalSearchResult {系統。 AppDomainUnloadedException}。我如何解決它? :) – Sarah 2014-11-25 08:54:00

+0

嗨@mar​​c_s,你能給我任何新的提示嗎?我仍然堅持我的方法,這也需要很長的時間來處理;結果:初始頁面需要永久加載.. :( – Sarah 2014-12-09 10:51:48