对于您上面的问题,是的,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;
}
}
如果您仍然希望使用枚举部分,甚至更好,为什么不只枚举特定 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/