You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure GraphServiceClient仅返回100条结果,如何获取全部?(C# .NET Core)

解决Graph API获取Exchange组仅返回100条的问题

Microsoft Graph API默认对列表类请求设置了100条的分页限制,要获取全部组数据,需要通过分页遍历的方式依次获取所有页面的结果。以下是两种可行的实现方式:

手动遍历分页结果

将代码改为异步实现(Azure Function支持异步执行,避免使用.Result造成线程阻塞),通过检查OdataNextLink判断是否存在下一页,循环获取所有数据:

public async Task<List<Group>> GetAllExchangeGroupsAsync(GraphServiceClient graphClient)
{
    var allGroups = new List<Group>();
    var currentPage = await graphClient.Groups.GetAsync();

    // 添加第一页的组数据
    allGroups.AddRange(currentPage.Value);

    // 循环获取后续所有分页数据
    while (!string.IsNullOrEmpty(currentPage.OdataNextLink))
    {
        currentPage = await graphClient.Groups.WithUrl(currentPage.OdataNextLink).GetAsync();
        allGroups.AddRange(currentPage.Value);
    }

    return allGroups;
}

使用Graph SDK的PageIterator简化遍历

利用Graph SDK提供的PageIterator工具类,自动处理分页逻辑:

public async Task<List<Group>> GetAllExchangeGroupsWithIteratorAsync(GraphServiceClient graphClient)
{
    var allGroups = new List<Group>();
    var groupsRequestInfo = graphClient.Groups.GetRequestInformation();
    
    // 创建分页迭代器
    var pageIterator = PageIterator<Group, GroupCollectionResponse>.CreatePageIterator(
        graphClient,
        await graphClient.RequestAdapter.SendAsync(groupsRequestInfo, () => new GroupCollectionResponse()),
        group =>
        {
            allGroups.Add(group);
            return true; // 返回true表示继续遍历所有项
        });

    // 执行迭代获取全部数据
    await pageIterator.IterateAsync();
    return allGroups;
}

注意事项

  • 确保Azure Function的触发方法标记为async Task类型,调用上述方法时使用await关键字
  • 应用需已配置Group.Read.All(或对应权限)的Microsoft Graph权限,确保有权限读取所有组数据
  • 若组数量庞大,建议添加错误捕获和重试逻辑,避免单次请求失败导致数据缺失

内容的提问来源于stack exchange,提问作者Brian Vind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:33:25