Active Directory异常asp .net

时间:2014-11-25 07:29:01

标签: asp.net active-directory

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中组的成员。它运作良好。尽管有时我得到一个奇怪的例外。

不支持指定的方法。 foreach(校长p in grp.GetMembers(true))是红色的(抱歉,我无法上传异常图片)。最奇怪的是它似乎随机抛出,如果我刷新页面它运作良好..

我试图在互联网上找到一个解决方案但现在没有幸福的新闻..

2 个答案:

答案 0 :(得分:0)

您应该以相反的方式执行此操作:获取用户,然后获取此用户所属的授权组 - 此调用(.GetAuthorizationGroups上的UserPrincipal 已经 以递归方式为您搜索群组!

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;
}

答案 1 :(得分:0)

我终于找到了解决方案!

我只需要添加我的域名,如下所示:

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

它马上解决了问题!

关于缓慢......我使用了cookie,遵循link