如何使用C# Graph SDK正确遍历多页PSTN通话日志?
正确使用Microsoft Graph .NET SDK遍历PSTN通话日志分页结果
你当前用Skip参数实现的分页属于偏移量分页,存在明显弊端:如果分页过程中数据发生新增或删除,会出现重复获取或遗漏数据的问题,而且也不符合Graph SDK的标准分页规范。官方推荐使用基于OdataNextLink的游标式分页,下面是两种规范的实现方式:
方式一:手动处理NextLink(灵活可控)
直接利用返回结果中的OdataNextLink构造下一页请求,无需手动计算偏移量:
var graphClient = new GraphServiceClient(authProvider); var allCallLogs = new List<Microsoft.Graph.Models.CallRecords.PstnCallLogRow>(); // 发起首次请求 var response = await graphClient .Communications .CallRecords .MicrosoftGraphCallRecordsGetPstnCallsWithFromDateTimeWithToDateTime( DateTimeOffset.Parse("2024-12-18"), DateTimeOffset.Parse("2024-12-28")) .GetAsync(); allCallLogs.AddRange(response.Value); // 循环获取所有后续分页 while (!string.IsNullOrEmpty(response.OdataNextLink)) { // 直接使用NextLink请求下一页,不需要重新设置日期范围和Skip参数 response = await graphClient .Communications .CallRecords .MicrosoftGraphCallRecordsGetPstnCallsWithFromDateTimeWithToDateTime() .GetAsync(config => config.Url = response.OdataNextLink); allCallLogs.AddRange(response.Value); }
方式二:使用SDK内置PageIterator(简洁高效)
Graph SDK提供了PageIterator工具类,自动封装了分页迭代逻辑,代码更简洁:
var graphClient = new GraphServiceClient(authProvider); var allCallLogs = new List<Microsoft.Graph.Models.CallRecords.PstnCallLogRow>(); // 构建初始请求 var pstnCallRequest = graphClient .Communications .CallRecords .MicrosoftGraphCallRecordsGetPstnCallsWithFromDateTimeWithToDateTime( DateTimeOffset.Parse("2024-12-18"), DateTimeOffset.Parse("2024-12-28")); // 初始化PageIterator,自动处理分页 var pageIterator = PageIterator<CallRecords.PstnCallLogRow, CallRecords.PstnCallLogRowCollectionResponse> .CreatePageIterator( graphClient, await pstnCallRequest.GetAsync(), callLog => { allCallLogs.Add(callLog); return true; // 返回true表示继续迭代所有页面 }); // 执行迭代,自动获取所有分页数据 await pageIterator.IterateAsync();
这两种方式都基于Graph API的游标分页机制,避免了偏移量分页的缺陷,是官方推荐的标准实现方式。
内容的提问来源于stack exchange,提问作者CSharpData
相关产品推荐
相关产品推荐

