Search code examples
c#microsoft-graph-api

Microsoft graph get all users returns only 100 users


Microsoft graph returns only 100 users, how could I get all the users from Microsoft graph

 var users = graphServiceClient
   .Users
   .Request()
   .GetAsync()
   .GetAwaiter()
   .GetResult();

How can I get all the users?


Solution

  • MS Graph uses paged output with default page size of 100 records. You've read just the first page of the default 100 users.

    You, probably, want something like this (queries are usually slow, that's why I've made them async):

    var users = await graphServiceClient
      .Users
      .Request()
      .Top(999)  // <- Custom page of 999 records (if you want to set it)
      .GetAsync()
      .ConfigureAwait(false);
    
    while (true) {
      //TODO: relevant code here (process users)
    
      // If the page is the last one
      if (users.NextPageRequest is null)
        break;
    
      // Read the next page
      users = await users
        .NextPageRequest
        .GetAsync()
        .ConfigureAwait(false);
    }