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

如何创建批量请求以收集用户列表的Object ID?[C#]

批量获取用户Object ID的C#实现方案

针对批量收集用户Object ID的需求,以下提供两种基于Microsoft Graph的实现方案,替代单个请求的低效方式:

方案一:使用$filter批量查询(适用于用户数量较少场景)

通过$filter参数一次性筛选多个邮箱地址,批量获取匹配用户的信息,再提取Object ID。这种方式请求次数少,适合用户数量不多的场景(注意Graph API的URL长度限制)。

// 示例:待查询的邮箱列表
List<string> roomEmails = new List<string> { "room1@contoso.com", "room2@contoso.com", "room3@contoso.com" };

// 构建多邮箱的OR筛选条件
string filterClause = string.Join(" or ", roomEmails.Select(email => $"mail eq '{email}'"));

// 发起批量查询,仅请求需要的字段以提升性能
var matchedUsers = await graphClient.Users
    .Request()
    .Filter(filterClause)
    .Select("Id, Mail")
    .GetAsync();

// 将结果转为邮箱与Object ID的映射字典,方便后续使用
Dictionary<string, string> emailToObjectIdMap = matchedUsers.ToDictionary(u => u.Mail, u => u.Id);

方案二:使用Graph Batch API(适用于大量用户场景)

当用户数量较多(超过$filter的URL长度限制),可以使用Batch API在单个HTTP请求中包含多个独立的用户查询请求,批量获取结果。

// 示例:待查询的邮箱列表
List<string> roomEmails = new List<string> { "room1@contoso.com", "room2@contoso.com", "room3@contoso.com" };

// 构建批量请求条目
var batchItems = new List<BatchRequestContentItem>();
int requestCounter = 1;
foreach (var email in roomEmails)
{
    var singleUserRequest = graphClient.Users[email].Request().Select("Id, Mail");
    batchItems.Add(new BatchRequestContentItem(requestCounter.ToString(), singleUserRequest));
    requestCounter++;
}

// 创建批量请求内容并发送
var batchContent = new BatchRequestContent(batchItems);
var batchResponse = await graphClient.Batch.Request().PostAsync(batchContent);

// 解析响应,提取每个邮箱对应的Object ID
Dictionary<string, string> emailToObjectIdMap = new Dictionary<string, string>();
foreach (var item in batchItems)
{
    var userResponse = await batchResponse.GetResponseByIdAsync<User>(item.Id);
    if (userResponse?.Value != null)
    {
        emailToObjectIdMap.Add(userResponse.Value.Mail, userResponse.Value.Id);
    }
}

注意事项

  • 始终使用Select方法指定仅需的字段(如Id和Mail),减少数据传输量和请求耗时。
  • 处理异常情况:若某个邮箱对应的用户不存在,需添加空值判断避免程序报错。
  • Batch API默认限制每个批次最多20个请求,若用户数量超出限制,需拆分多个批次请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:05:36