如何批量获取用户ID以调用Microsoft Graph API批量状态查询?
解决方案
1. 批量获取用户ID(通过邮箱)
你可以借助Microsoft Graph的$filter查询参数,搭配in操作符一次性查询多个邮箱对应的用户ID,彻底避免逐个请求带来的延迟问题。示例代码如下:
// 假设你有目标邮箱列表 List<string> targetEmails = new List<string> { "user1@contoso.com", "user2@contoso.com", ... }; // 构造批量查询的filter条件,邮箱需用单引号包裹并以逗号分隔 string filterCondition = $"mail in ({string.Join(", ", targetEmails.Select(e => $"'{e}'"))})"; // 发起批量查询,仅获取需要的Id和Mail属性 var batchUsers = await _graphServiceClient.Users .Request() .Filter(filterCondition) .Select("Id, Mail") .GetAsync(); // 转为字典,方便快速通过邮箱映射到用户ID Dictionary<string, string> emailIdMap = batchUsers.ToDictionary(u => u.Mail, u => u.Id);
一次请求即可获取所有目标用户的ID,大幅降低请求次数和整体延迟。
2. 为何Select中添加u.Presence返回null
Presence不属于User资源的可查询属性,无法通过User端点的查询直接获取。Microsoft Graph将用户状态作为独立资源,必须通过专门的Presence接口获取:
- 单个用户状态:
_graphServiceClient.Users[userId].Presence.Request().GetAsync() - 批量用户状态:就是你当前使用的
GetPresenceByUserIds方法
因此在User查询的Select中包含Presence字段时,Graph API会直接返回null,这是API的设计限制。
内容的提问来源于stack exchange,提问作者bmoolman
相关产品推荐
相关产品推荐

