求助:使用Microsoft.Graph.GraphServiceClient处理Graph API分页的示例
使用GraphServiceClient处理Graph API分页示例
当你的查询结果超过Graph API默认分页限制(通常为100条)时,返回的UserCollectionResponse会包含OdataNextLink属性,你可以通过以下方式循环获取所有分页数据:
完整代码示例
// 准备存储所有用户的集合 var allUsers = new List<User>(); // 发起首次请求,获取第一页数据 var currentResponse = await client.Users .GetAsync(rc => { rc.QueryParameters.Select = new[] { "userPrincipalName", "displayName", "id" }; }); // 将第一页数据加入集合 if (currentResponse.Value != null) { allUsers.AddRange(currentResponse.Value); } // 循环处理后续分页 while (!string.IsNullOrEmpty(currentResponse.OdataNextLink)) { // 利用OdataNextLink发起下一页请求 currentResponse = await client.Users .WithUrl(currentResponse.OdataNextLink) .GetAsync(); // 将新页数据追加到总集合 if (currentResponse.Value != null) { allUsers.AddRange(currentResponse.Value); } } // 此时allUsers包含所有分页返回的用户数据
关键说明
- 首次请求返回的
currentResponse是UserCollectionResponse类型,其中Value存储当前页的用户列表,OdataNextLink是下一页的请求地址 - 使用
.WithUrl()方法直接传入OdataNextLink,即可复用原请求上下文发起分页请求,无需重新构建查询参数 - 循环终止条件是
OdataNextLink为空,代表所有数据已获取完毕
内容的提问来源于stack exchange,提问作者Kevin O'Donovan
相关产品推荐
相关产品推荐

