Microsoft Graph API 分页无法从 Azure AD 获取所有用户

问题描述

我们正在使用 Microsoft Graph API Beta 版,使用以下代码从 Azure AD 中检索所有用户。 API 在响应中仅返回 100 个用户,为了使用分页响应,我们尝试了 NextPageRequest 属性。但它总是为 null 属性返回 NextPageRequest。因此,它永远不会进入 while 循环来检索其他用户

测试版 SDK 版本:4.0.1.0

代码

                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;

我关注的参考链接

对此的任何帮助将不胜感激!

解决方法

下面的代码对我来说非常好。

localhost

在 Azure Active Directory 用户刀片中检查您的用户并查看其中存在多少用户。您还可以通过简单地使用 $top 查询参数扩展代码来测试用户数量是否超过 100,该参数为每个请求提供 998 条记录,如下所示。

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;
        }

您还可以在 Graph Explorer 中测试图谱 API 调用。

编辑:

经过长时间的研究,我发现这是 Microsoft Graph Beta SDK 中的一个错误,因为它总是在 IGraphServiceUsersCollectionPage users = await graphClient.Users .Request() .Top(998) .GetAsync(); 中发送空值。但这里有趣的是,它发送 NextPageRequest 属性中的 odata.nextLink。因此,如果您使用的是 Graph Beat SDK,请使用以下代码。

AdditionalData

注意:Microsoft 不建议在生产环境中使用其 Graph Beta version,因为它们可能会发生变化。