GroupPrincipal throw"System.Runtime.InteropServices.COMException(0x8007200A):指定的目录服务属性或值不存在."

Jim*_*Jim 3 active-directory account-management c#-4.0 groupprincipal

System.DirectoryServices.AccountManagement用来查询用户,然后找到该用户的组.

var _principalContext = new PrincipalContext(ContextType.Domain, domainAddress, adContainer, adQueryAccount, adQueryAccountPassword);
var user = UserPrincipal.FindByIdentity(_principalContext, IdentityType.SamAccountName, account);
var userGroups = user.GetGroups(); 

foreach (var group in userGroups.Cast<GroupPrincipal>())
{
    //////////////////////////////////////////////////////
    // getting the underlying DirectoryEntry shown
    // to demonstrate that I can retrieve the underlying
    // properties without the exception being thrown
    DirectoryEntry directoryEntry = group.GetUnderlyingObject() as DirectoryEntry;

    var displayName = directoryEntry.Properties["displayName"];

    if (displayName != null && displayName.Value != null)
        Console.WriteLine(displayName.Value);
    //////////////////////////////////////////////////////

    Console.WriteLine(group.DisplayName);// exception thrown here...
}
Run Code Online (Sandbox Code Playgroud)

我可以获取底层DirectoryEntry对象并转储其属性和值,但只要GroupPrincipal.DisplayName访问属性(或任何属性),就会抛出以下异常:

"System.Runtime.InteropServices.COMException(0x8007200A):指定的目录服务属性或值不存在\在System.DirectoryServices.DirectoryEntry.Bind(布尔throwIfFail)R \n\r \n\r \n在系统. DirectoryServices.DirectoryEntry.Bind(个)\ r \n在System.DirectoryServices.DirectoryEntry.get_SchemaEntry(个)\ r \n在System.DirectoryServices.AccountManagement.ADStoreCtx.IsContainer(的DirectoryEntry DE)\ r \n在System.DirectoryServices.AccountManagement. ADStoreCtx..ctor(DirectoryEntry ctxBase,Boolean ownCtxBase,String username,String password,ContextOptions options)\ r \n位于System.DirectoryServices.AccountManagement.PrincipalContext的System.DirectoryServices.AccountManagement.PrincipalContext.CreateContextFromDirectoryEntry(DirectoryEntry entry)\ r \n .DoLDAPDirectoryInitNoContainer(个)\ r \n在System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit(个)\ r \n在System.DirectoryServices.AccountManagement.PrincipalContext.Initialize(个)\ r \n在System.DirectoryServices.Ac count.PrincipalContext.get_QueryCtx()\ r \n在System.DirectoryServices.AccountManagement.Principal.HandleGet [T](T¤tValue,String name,LoadState&state)\ r \n在System.DirectoryServices.AccountManagement.Principal.get_DisplayName( )\ r \n在ConsoleApplication9.Program.Main(String [] args)"

为什么我能够转储底层的原始属性DirectoryEntry但不能直接调用任何属性GroupPrincipal?什么会导致这个例外?请注意,这不会发生在"域用户"组中,而是后续组,它会...

Jim*_*Jim 5

我找到了解决方案.如果我将上下文传递给GetGroups方法,它就可以工作.

var user = UserPrincipal.FindByIdentity(_principalContext, IdentityType.SamAccountName, account);
var userGroups = user.GetGroups(_principalContext);
Run Code Online (Sandbox Code Playgroud)

显然,这会将检索到的组限制在与上下文关联的域中.虽然这不直观,因为首先使用上下文来检索用户!

这使我相信必须先从其他域中返回组,并且权限是这样的,以防止访问该信息.