Search code examples
.net-coredirectoryservices

UnsafeNativeMethods exception with GroupPrincipal.getMembers()


I recently started porting our .Net 4.6 web application to .Net Core 2.0 and am having some problems regarding the access to System.DirectoryServices.AccountManagement

I want to access GroupPrincipal.getMembers() but keep getting an UnsafeNativeMethods exception:

System.DirectoryServices.Interop.UnsafeNativeMethods+IAds.GetInfoEx(object vProperties, int lnReserved)
System.DirectoryServices.DirectoryEntry.RefreshCache(String[] propertyNames)
System.DirectoryServices.AccountManagement.RangeRetriever.GetNextChunk()
System.DirectoryServices.AccountManagement.RangeRetriever.MoveNext()
System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.GetNextEnum()
System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.MoveNextMemberEnum()
System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.MoveNext()
System.DirectoryServices.AccountManagement.FindResultEnumerator.MoveNext()
AspNetCore._Views_Groups_Show_cshtml+<ExecuteAsync>d__0.MoveNext() in Show.cshtml
+
    @foreach (var p in Model.GetMembers())
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

The code in the Show.cshtml:

@using System.DirectoryServices.AccountManagement
@model GroupPrincipal

@foreach (var p in Model.GetMembers())
{
  ...
}

The exception: System.Exception: An operations error occurred.

Already tried moving the code from the view into the controller and marking it with unsafe but that doesn't help either.

Code is already running as domain admin, can access all users etc. Just the method calls don't work.

What's the correct way to handle this?


Solution

  • Ok, seems that I've found a solution/workaround:

    I saw that it processes the principals and throws an exception after processing them. So I just put the principals in another list and caught the exception.

    The new list contains all principals and can be accessed without problems.

    List<Principal> members = new List<Principal>();
    
    try
    {
        members.AddRange(group.GetMembers());
    } 
    catch (Exception)
    {
        ; // do nothing
    }
    

    Must be a bug in the .NET core implementation of System.DirectoryServices.AccountManagement