获取给定UserPrincipal的组列表

TTC*_*TCG 9 c# active-directory userprincipal

我想获取用户所在的组列表.

这是我的代码:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain.ac.uk",   "DC=mydomain,DC=AC,DC=UK", "user", "password");

UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "MyUser");

PrincipalSearchResult<Principal> results = user.GetGroups();

foreach(Principal p in results)
{
   Response.Write(p.Name);
}
Run Code Online (Sandbox Code Playgroud)

当我跑,我在线上得到以下错误 Response.Write(p.Name);

System.Runtime.InteropServices.COMException:指定的目录服务属性或值不存在.

当我检查结果的计数时,它返回9,第一组是DomainUsers.

如何迭代列表中的所有9个组?谢谢.

以下是我获得的用户列表:

在此输入图像描述

小智 5

如PrincipalContext Class中所述省略LDAP容器属性时,运行代码的用户必须具有对默认UserContainer(即CN=Users,DC=yourDomain,DC=COM)和ComputersContainer(即CN=Computers,DC=yourDomain,DC=COM)的读取权限.

如果用户没有所需的权限,您将收到以下错误消息:

指定的目录服务属性或值不存在

  • 'context.Container'抛出了类型'System.NullReferenceException'字符串{System.NullReferenceException}的异常

  • ((new System.Linq.SystemCore_EnumerableDebugView(groups)).Items [5]).Description'抛出类型'System.Runtime.InteropServices.COMException'的异常'{System.Runtime.InteropServices.COMException}

请查看我的博客发布 PrincipalContext的身份验证问题


Sin*_*tic 1

尝试类似的东西

foreach(Principal p in results)
{ 
   if (p is GroupPrincipal) 
      Response.Write(p.DisplayName); 
}
Run Code Online (Sandbox Code Playgroud)

我知道这听起来很愚蠢,但它过去对我有用。您的结果看起来实际上只找到 1 个安全组和 8 个“其他”类型的组。那些“其他”群体可能不具备这些属性。