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

如何使用C#从Azure AD获取完整的用户属性?

如何使用C#从Azure AD获取所有用户属性?

这个问题我之前踩过坑!原因很直白:Microsoft Graph API默认只会返回用户的基础属性子集,像Department、Mail这类属性不在默认返回列表里,所以你拿到的自然都是null。解决方法就是主动声明要获取的属性,具体操作如下:

核心问题:默认属性集的限制

当你调用graphClient.Users.Request().GetAsync()时,Graph API只返回一组预定义的基础属性(比如DisplayName、GivenName、Surname、UserPrincipalName等),其他属性需要你显式指定才能返回。

解决方案:用Select()方法指定要获取的属性

你需要在请求链中添加Select(),把所有需要的属性列进去。比如你要获取Department、Mail、JobTitle等字段,就可以按下面的方式修改代码:

修改后的完整代码

public async Task<List<ResultsItem>> GetUsers(GraphServiceClient graphClient)
{
    List<ResultsItem> items = new List<ResultsItem>();
    
    // 显式指定需要的用户属性,按需添加你需要的字段
    IGraphServiceUsersCollectionPage users = await graphClient.Users
        .Request()
        .Select("Id,DisplayName,Department,GivenName,Surname,UserPrincipalName,Mail,JobTitle,OfficeLocation") // 这里列出所有要获取的属性
        .GetAsync();

    // 处理分页:Graph API默认最多返回100条数据,需遍历所有页面才能拿到全部用户
    while (users != null)
    {
        foreach (User user in users)
        {
            string displayName = user.DisplayName ?? "";
            if (!displayName.StartsWith("Conf Room"))
            {
                items.Add(new ResultsItem
                {
                    Mail = user.Mail,
                    Display = user.DisplayName,
                    Id = user.Id,
                    Department = user.Department,
                    GivenName = user.GivenName,
                    Surname = user.Surname,
                    UserPrincipalName = user.UserPrincipalName,
                    // 如果添加了其他属性(比如JobTitle),这里也要对应赋值
                    JobTitle = user.JobTitle
                });
            }
        }

        // 获取下一页数据
        if (users.NextPageRequest != null)
        {
            users = await users.NextPageRequest.GetAsync();
        }
        else
        {
            break;
        }
    }

    var jsonEmployees = JsonConvert.SerializeObject(items);
    return items;
}

关键注意点

  • 属性名称要匹配Graph API字段:SDK里的User类属性是帕斯卡命名(比如Department),Select()里写department或Department都可以,但建议和SDK属性名保持一致,避免混淆。
  • 必须处理分页:如果你的Azure AD用户超过100个,默认请求只会返回第一页,必须通过NextPageRequest遍历所有页面才能拿到全部数据。
  • 自定义扩展属性:如果需要获取自定义添加的用户属性(比如extension_xxx_xxx),除了在Select()里指定,还要确保你的应用有对应的读取权限,且属性已在Azure AD中正确配置。

验证小技巧

如果某些属性还是null,可以先在Graph Explorer中测试请求:

GET https://graph.microsoft.com/v1.0/users?$select=id,displayName,department

看看返回的JSON里有没有对应属性值,先排除是Azure AD中数据未填充的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:00:44