對於你上面的問題,是的AD有時有點慢取決於負載,而不是專注於爲什麼不改變你的邏輯,而不是枚舉所有的用戶組爲什麼不檢查用戶是否是組的成員。爲了在這裏實現它的代碼是
/// <summary>
/// Checks if user is a member of a given group
/// </summary>
/// <param name="sUserName">The user you want to validate</param>
/// <param name="sGroupName">The group you want to check the membership of the user</param>
/// <returns>Returns true if user is a group member</returns>
public bool IsUserGroupMember(string sUserName, string sGroupName)
{
UserPrincipal oUserPrincipal = GetUser(sUserName);
GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
if (oUserPrincipal == null || oGroupPrincipal == null)
{
return oGroupPrincipal.Members.Contains(oUserPrincipal);
}
else
{
return false;
}
}
或者即使你仍想喜歡使用ennumeration一部分,爲什麼不ennumerate只能在特定的OU的組,而不是像這樣
/// <summary>
/// Gets a list of the users group memberships
/// </summary>
/// <param name="sUserName">The user you want to get the group memberships</param>
/// <param name="sOU">The OU you want to search user groups from</param>
/// <returns>Returns an arraylist of group memberships</returns>
public ArrayList GetUserGroups(string sUserName, string sOU)
{
ArrayList myItems = new ArrayList();
UserPrincipal oUserPrincipal = GetUser(sUserName);
PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups(GetPrincipalContext(sOU));
foreach (Principal oResult in oPrincipalSearchResult)
{
myItems.Add(oResult.Name);
}
return myItems;
}
/// <summary>
/// Gets the principal context on specified OU
/// </summary>
/// <param name="sOU">The OU you want your Principal Context to run on</param>
/// <returns>Retruns the PrincipalContext object</returns>
public PrincipalContext GetPrincipalContext(string sOU)
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword);
return oPrincipalContext;
}
整個目錄更好
最後,作爲一個提示,如果您重視安全而不是速度,那麼我不會建議IsPostback == false
,這樣如果某個用戶的安全組成員身份有任何更改,那麼您將能夠在下一個進程中更好地捕獲它。
對於全面實施AD方法請參閱這裏 如果您使用的是.NET 2.0
http://anyrest.wordpress.com/2010/02/01/active-directory-objects-and-c/
,或者如果您使用的是.NET 3.5或4.0
http://anyrest.wordpress.com/2010/06/28/active-directory-c/
謝謝!這正是我現在正在做的 - 我的老闆重寫了他的組員成員函數,通過正確地輪詢Active Directory來加快結果。我不認爲我在問題中指定了這一點,但他的組員成員函數最初將所有用戶的組從AD中移出並遍歷它們以檢查所請求的組,這就是爲什麼我決定將所有組拉回一次,並從他的團體成員函數中分別檢查我的三個小組。 – jwiscarson 2010-11-02 22:53:22