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

.NET8控制台应用中PageIterator如何配置WithAppOnly选项?

解决PageIterator忽略WithAppOnly选项的问题

1. 给PageIterator添加请求选项

PageIterator支持通过委托修改后续分页请求的配置,只需在创建迭代器时指定WithAppOnly(),确保所有分页请求都使用应用权限:

var devicelist = new List<DeviceModel>();

var pageIterator = PageIterator<ManagedDevice, ManagedDeviceCollectionResponse>.CreatePageIterator(
    graphServiceClient,
    devices,
    (device) =>
    {
        devicelist.Add(DeviceModelMapper.MapFromManagedDevice(device));
        return true;
    },
    // 为每一页请求注入WithAppOnly选项
    request => request.WithAppOnly()
);

await pageIterator.IterateAsync();

2. 设置Graph客户端默认使用WithAppOnly

全局配置客户端,让所有请求自动应用WithAppOnly,无需每次单独设置:

方式一:通过中间件配置

var credential = new ClientCertificateCredential(tenantId, clientId, certificate);
var scopes = new[] { "https://graph.microsoft.com/.default" };

var graphClient = new GraphServiceClient(
    credential,
    scopes,
    requestMiddlewareOptions: new MicrosoftGraphRequestMiddlewareOptions
    {
        PreRequestMiddleware = (requestContext) =>
        {
            requestContext.RequestOptions.WithAppOnly();
            return Task.CompletedTask;
        }
    });

方式二:添加默认请求选项

var graphClient = new GraphServiceClient(credential, scopes);
// 全局添加应用权限请求选项
graphClient.RequestAdapter.AddDefaultRequestOption(new AppOnlyOption());

配置后,所有通过该客户端发起的请求(包括PageIterator的分页请求)都会自动使用应用权限认证。

3. 手动实现分页遍历

如果不想使用PageIterator,可手动处理分页逻辑,确保每一页请求都带上WithAppOnly:

var devicelist = new List<DeviceModel>();
var currentPage = await graphServiceClient.DeviceManagement.ManagedDevices.GetAsync(r => r.Options.WithAppOnly());

while (currentPage != null)
{
    // 处理当前页数据
    foreach (var device in currentPage.Value)
    {
        devicelist.Add(DeviceModelMapper.MapFromManagedDevice(device));
    }

    // 请求下一页
    if (!string.IsNullOrEmpty(currentPage.OdataNextLink))
    {
        currentPage = await graphServiceClient
            .DeviceManagement.ManagedDevices
            .WithUrl(currentPage.OdataNextLink)
            .GetAsync(r => r.Options.WithAppOnly());
    }
    else
    {
        break;
    }
}

内容的提问来源于stack exchange,提问作者mickael ponsot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 15:45:13