简体   繁体   中英

Get ONLY the count of members of 'GROUP' type from an AAD group using Graph API

Is there a Graph API to get the count of members of a specific type from AAD group? For example, consider the following AAD group:

在此处输入图像描述

This group contains 2 members of type 'Group'. Is there a Graph API to get that count (2)? Or should I get all members from the group and do some filtering to get the members of 'Group' type as follows:

var groups = new List<Guid>();
var response = await _graphServiceClient
           .Groups[groupId]
           .TransitiveMembers
           .Request()
           .Top(999)
           .GetAsync();

groups.AddRange(ToGroups(response));

private IEnumerable<Guid> ToGroups(IEnumerable<DirectoryObject> members)
{
            foreach (var directoryObj in fromGraph)
            {
                switch (directoryObj)
                {                    
                    case Group group:
                        yield return Guid.Parse(group.Id);
                        break;
                    default:
                        break;
                }
            }
}

You can cast microsoft.graph.group type like this

GET https://graph.microsoft.com/v1.0/groups/{groupId}/transitiveMembers/microsoft.graph.group

To retrieve the count the query will be

GET https://graph.microsoft.com/v1.0/groups/{groupId}/transitiveMembers/microsoft.graph.group/$count

To achieve this in C# I would create request, add casting and count parameter to request URL. Then create http request message and sent this message, read the response and parse the response as integer.

var requestUrl = _graphServiceClient.Groups[groupId].TransitiveMembers.Request().RequestUrl;

// add casting and count query
requestUrl = $"{requestUrl}/microsoft.graph.group/$count";

// Create the request message
var hrm = new HttpRequestMessage(HttpMethod.Get, requestUrl);
// $count requires header ConsistencyLevel
hrm.Headers.Add("ConsistencyLevel", "eventual");

// Authenticate (add access token) our HttpRequestMessage
await _graphServiceClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);

// Send the request and get the response.
var response = await _graphServiceClient.HttpProvider.SendAsync(hrm);

// read the content and parse it as an integer
var content = await response.Content.ReadAsStringAsync();
var groupCount = int.Parse(content);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM