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

如何用C#调用Microsoft Graph API按ID列表获取含组ID的用户

C#调用Microsoft Graph API获取带所属组ID的用户列表

1. 前置准备

  • 安装必要的NuGet包:
    Install-Package Microsoft.Graph
    Install-Package Microsoft.Identity.Client
    
  • 在Azure AD注册应用程序,添加应用权限:
    • User.Read.All(允许读取所有用户信息)
    • Group.Read.All(允许读取所有组信息)
      完成后需授予管理员同意。

2. 实现认证与Graph客户端初始化

先实现一个获取GraphServiceClient的方法,采用客户端凭据流(适合后台服务场景):

using Microsoft.Graph;
using Microsoft.Identity.Client;

public static GraphServiceClient GetGraphClient(string tenantId, string clientId, string clientSecret)
{
    var scopes = new[] { "https://graph.microsoft.com/.default" };
    
    var clientApplication = ConfidentialClientApplicationBuilder
        .Create(clientId)
        .WithTenantId(tenantId)
        .WithClientSecret(clientSecret)
        .Build();

    var authenticationProvider = new ClientCredentialProvider(clientApplication, scopes);
    
    return new GraphServiceClient(authenticationProvider);
}

3. 核心业务逻辑实现

先定义DTO存储包含组ID的用户信息,再实现批量获取用户并关联组ID的方法:

// 自定义DTO,存储所需用户信息与所属组ID列表
public class UserWithGroupsDto
{
    public string Id { get; set; }
    public string DisplayName { get; set; }
    public string UserPrincipalName { get; set; }
    public List<string> GroupIds { get; set; } = new List<string>();
}

public static async Task<List<UserWithGroupsDto>> GetUsersWithGroupIdsAsync(GraphServiceClient graphClient, List<string> userIds)
{
    var result = new List<UserWithGroupsDto>();
    
    // 批量获取用户基本信息
    var userRequests = userIds.Select(id => graphClient.Users[id].Request().Select(u => new { u.Id, u.DisplayName, u.UserPrincipalName }));
    var userTasks = userRequests.Select(req => req.GetAsync());
    
    var users = await Task.WhenAll(userTasks);
    
    foreach (var user in users)
    {
        if (user == null) continue;
        
        var userDto = new UserWithGroupsDto
        {
            Id = user.Id,
            DisplayName = user.DisplayName,
            UserPrincipalName = user.UserPrincipalName
        };
        
        // 获取用户所属组ID(处理分页)
        var groupsPage = await graphClient.Users[user.Id].MemberOf.Request().GetAsync();
        do
        {
            userDto.GroupIds.AddRange(groupsPage.Where(g => g.ODataType == "#microsoft.graph.group").Select(g => g.Id));
            groupsPage = await groupsPage.NextPageRequest?.GetAsync();
        } while (groupsPage != null);
        
        result.Add(userDto);
    }
    
    return result;
}

4. 调用示例

在主逻辑中调用上述方法:

public static async Task Main(string[] args)
{
    // 替换为你的Azure AD租户ID、客户端ID、客户端密钥
    var tenantId = "your-tenant-id";
    var clientId = "your-client-id";
    var clientSecret = "your-client-secret";
    
    var targetUserIds = new List<string> { "user-id-1", "user-id-2", "user-id-3" };
    
    var graphClient = GetGraphClient(tenantId, clientId, clientSecret);
    var usersWithGroups = await GetUsersWithGroupIdsAsync(graphClient, targetUserIds);
    
    // 输出结果
    foreach (var user in usersWithGroups)
    {
        Console.WriteLine($"用户ID: {user.Id}, 姓名: {user.DisplayName}");
        Console.WriteLine("所属组ID列表:");
        foreach (var groupId in user.GroupIds)
        {
            Console.WriteLine($"- {groupId}");
        }
        Console.WriteLine("------------------------");
    }
}

5. 优化建议

  • 减少API调用次数:使用Graph API的批量请求(Batch)功能,将多个用户的组查询合并为一个请求,降低网络开销。
  • 异常处理:添加try-catch块处理API调用中的异常(如用户不存在、权限不足等)。
  • 权限最小化:如果仅需读取特定用户的组,可考虑使用委托权限而非应用权限(需用户登录上下文)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:16:16