Microsoft Graph api code in C# displays only limited number of users

心已入冬 提交于 2020-03-12 06:07:33

问题


I am running below Microsoft Graph Api code:

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace AADConsole2
{
    class Program
    {

        private const string aadInstance = "https://login.microsoftonline.com/{0}";
        //  private const string ResourceUrl = "https://graph.windows.net";

        private const string resource = "https://graph.microsoft.com";
        private const string GraphServiceObjectId = "XXX";
        private const string TenantId = "XXX";
        private const string tenant = "XXXX.onmicrosoft.com";
        private const string ClientId = "XXX";
        private static string appKey= "XXXX";
        static string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, aadInstance, tenant);

        private static HttpClient httpclient = new HttpClient();
        private static AuthenticationContext context = null;
        private static ClientCredential credential = null;


        static void Main(string[] args)
        {

            context = new AuthenticationContext(authority);
            credential = new ClientCredential(ClientId, appKey);
            Task<string> token = GetToken();
            token.Wait();
            Console.WriteLine(token.Result);
            Task<string> users = GetUsers(token.Result);
            users.Wait();
            Console.WriteLine(users.Result);
            Console.ReadLine();
        }

        private static async Task<string> GetUsers(string result) {
            //throw new NotImplementedException();
            string users = null;
            var uri = "https://graph.microsoft.com/v1.0/users";
            httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
            var getResult = await httpclient.GetAsync(uri);

            if(getResult.Content != null)
            {
                users = await getResult.Content.ReadAsStringAsync();

            }
            return users;

        }


        private static async Task<string> GetToken()
        {
            AuthenticationResult result = null;
            string token = null;
            result = await context.AcquireTokenAsync(resource, credential);
            token = result.AccessToken;
            return token;



        }
    }
}

I am getting the results of user detail printed on console ,but only limited number of users are printed. i.e only whose name starts with letter 'a'. And also some user details are missing. How to get all user details .Am i missing some api in this code? Thanks.


回答1:


Most Microsoft Graph endpoints return paged result sets. Your initial request only returns the first page of data. To retrieve the next page, you follow the URI provided in the @odata.nextLink property. Each subsequent page will return the next page's @odata.nextLink until you the last page of data (denoted by the lack of a @odata.nextLink in the result). There is a step-by-step walkthrough of how this works at Paging Microsoft Graph data in your app.

The single most important tip I can give you here is to not use $top to force it to return large pages of data. This is an extremely inefficient method for calling the API and inevitably leads to network errors and request throttling. It also doesn't eliminate the need to handle paging since even $top=999 (the maximum) can still return multiple pages.

Implement paging, keep your page sizes small, and process the results after each page is returned before moving on to the next page. This will ensure you capture all of the data and allow your application to pick up where it left off should it encounter any errors during processing.




回答2:


Something like this will get all of your users. Also if you want properties outside of the default you need need to specify them with a select. Not all properties are returned by default.

            String Properties = "Comma Separated List of Properties You actaully Need";
            List<User> AllUsers = new List<User>();
            IGraphServiceUsersCollectionPage users = graphServiceClient.Users
                                                        .Request()
                                                        .Select(Properties)
                                                        .GetAsync()
                                                        .Result;

            do
            {
                QueryIncomplete = false ;
                AllUsers.AddRange(users);
                if (users.NextPageRequest != null)
                {
                    users = users.NextPageRequest.GetAsync().Result;
                    QueryIncomplete = true;
                }

            }while (QueryIncomplete);

            return AllUsers;


来源:https://stackoverflow.com/questions/60282929/microsoft-graph-api-code-in-c-sharp-displays-only-limited-number-of-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!