尝试解析跨存储引用时,无法解析目标主体的 SID。错误代码为 1332

While trying to resolve a cross-store reference, the SID of the target principal could not be resolved. The error code is 1332

从组中获取用户时,给出异常消息 "While trying to resolve a cross-store reference, the SID of the target principal could not be resolved. The error code is 1332."

        PrincipalContext ctx = null;
        if (!string.IsNullOrWhiteSpace(adUserName))
        {
            ctx = new PrincipalContext(ContextType.Domain, domainName, adUserName, adPassword);
        }
        else
        {
            ctx = new PrincipalContext(ContextType.Domain, domainName);
        }
        var groupNames = commaSeparatedGroupNames.Split(',');
        IEnumerable<Principal> users = null;
        foreach (var groupName in groupNames)
        {
            if (!string.IsNullOrWhiteSpace(groupName))
            {
                var userGroup = GroupPrincipal.FindByIdentity(ctx, groupName.Trim());
                if (userGroup == null)
                    throw new InvalidOperationException("Active Directory Group Not Found :: " + groupName);

                var usersInGroup = userGroup.GetMembers();

                if (users == null)
                {
                    users = usersInGroup;
                }
                else
                {
                    users = users.Union(usersInGroup);
                }
            }
        }

        return users;

做的时候

foreach (UserPrincipal user in users)

我遇到了错误。 我可以检查此错误或在循环期间从列表中跳过此成员的任何建议。

我认为您的问题与 group.GetMembers() 的 return 类型有关,它不一定是 UserPrincipal,而是 Principal

所以您可能想检查 PrincipalUserPrincipal 还是 GroupPrincipal

foreach(var principal in groupMembers)

在你的情况下会是更好的选择。

我昨天刚遇到同样的问题,这是我在这个 link:

找到的最佳答案
IEnumerator<Principal> enumerator = members.GetEnumerator();
while (enumerator.MoveNext())
{
    try
    {
        Principal member = enumerator.Current;
        Console.WriteLine("{0}\r\n\t{1}\r\n\t{2}",member.ToString(),member.Guid,member.DistinguishedName);
    } catch (Exception ex) {
        Console.WriteLine(ex.Message);
    }
}

这就是迭代 IEnumerable 集合的方式 'manually'。如果它是未定义的 SID 或其他一些问题,它使您有机会尝试获取主体并捕获异常。

Sandra 的解决方案几乎是正确的,但是在 MoveNext() 方法上会抛出异常,因此如果将 try..catch 块放在其中,它将不起作用。

var enumerator = members.GetEnumerator();

var moveNext = true;

while (moveNext)
{
    try
    {
        moveNext = enumerator.MoveNext();

        if (moveNext)
        {
            Principal member = enumerator.Current;
        
            Console.WriteLine("{0}\r\n\t{1}\r\n\t{2}", member, member.Guid, member.DistinguishedName);
        }
    } 
    catch (Exception ex) 
    {
        Console.WriteLine(ex.Message);
    }
}