We are using Microsoft Graph API Beta version to retrieve all users from the Azure AD using below code. API returns only 100 users in the response and to use paginated response we tried NextPageRequest
property. But it always return null
for the NextPageRequest
property. And due to that it never enters to the while loop to retrieve rest of the users.
Beta SDK version: 4.0.1.0
Code:
List<User> usersList = new List<User>();
IGraphServiceUsersCollectionPage users = await graphClient.Users.Request().GetAsync();
// Add the first page of results to the user list
usersList.AddRange(users.CurrentPage);
// Fetch each page and add those results to the list
while (users.NextPageRequest != null)
{
users = await users.NextPageRequest.GetAsync();
usersList.AddRange(users.CurrentPage);
}
log.Info("Users count: " + usersList.Count.ToString());
return usersList;
Reference links that I followed:
Any help on this will be appreciated!
The below code works perfectly fine for me.
public static async Task<List<User>> getUsers()
{
List<User> usersList = new List<User>();
graphClient.BaseUrl = "https://graph.microsoft.com/beta";
IGraphServiceUsersCollectionPage users = await graphClient.Users
.Request()
.GetAsync();
usersList.AddRange(users.CurrentPage);
while (users.NextPageRequest != null)
{
users = await users.NextPageRequest.GetAsync();
usersList.AddRange(users.CurrentPage);
}
return usersList;
}
Check your users in Azure Active Directory Users Blade and see how many users are present in it. And also you can test the number of users if there are more than 100 or not by simply extending the code with $top query parameter which gives 998 records per request as shown below.
IGraphServiceUsersCollectionPage users = await graphClient.Users
.Request()
.Top(998)
.GetAsync();
You can also test Graph API calls in Graph Explorer.
EDIT:
After a long research I got to find out that its a bug in Microsoft Graph Beta SDK as it is always sending null in the NextPageRequest
. But the interesting thing here is, it is sending the odata.nextLink
in the AdditionalData
property. So use the below code if you are using Graph Beat SDK.
public static async Task<List<User>> getUsers()
{
List<User> usersList = new List<User>();
IGraphServiceUsersCollectionPage users = await graphClient.Users
.Request()
.GetAsync();
usersList.AddRange(users.CurrentPage);
try
{
while (users.AdditionalData["@odata.nextLink"].ToString() != null)
{
users.InitializeNextPageRequest(graphClient, users.AdditionalData["@odata.nextLink"].ToString());
users = await users.NextPageRequest.GetAsync();
usersList.AddRange(users.CurrentPage);
}
}
catch(Exception e)
{
}
return usersList;
}
Note: Microsoft doesn't suggest to use its Graph Beta version in Production as they are subjected to change.