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

如何使用GraphServiceClient获取Azure AD B2C自定义属性

如何通过C#的GraphServiceClient获取ADB2C用户的自定义扩展属性值?

我有一个附带自定义属性的ADB2C用户列表,需要通过编程方式获取该属性。

通过PowerShell的AzureAD扩展查询可以看到该属性(GUID已简化):

> Get-AzureADUser -ObjectId 00000e9b... | select *
ExtensionProperty              : {[odata.type, Microsoft.DirectoryServices.User], [createdDateTime, 24.09.2021 6:55:48], [employeeId, ], [onPremisesDistinguishedName, ]...}
DeletionTimestamp              :
ObjectId                       : 00000e9b...
ObjectType                     : User
... some other keys ...

>> Get-AzureADUser -ObjectId  00000e9b... | select *  -ExpandProperty ExtensionProperty

Key                                                   Value
---                                                   -----
odata.type                                            Microsoft.DirectoryServices.User
createdDateTime                                       24.09.2021 6:55:48
... some other keys ...
extension_05700734c8154786b58d437faf3d30c7_customerId 501cd02e...

可见存在名为extension_05700734c8154786b58d437faf3d30c7_customerId的属性,值为501cd02e...。我尝试用C#和GraphServiceClient获取该属性与ObjectId,代码如下:

var result = await graphClient.Users
      .Request()
      .Select("id,Identities,DisplayName,extension_05700734c8154786b58d437faf3d30c7_customerId")
      .Top(999)
      .GetAsync();

但序列化JSON后,该属性出现在AdditionalData中且仅显示ValueKind,无法拿到实际值:

{
   ... many NULL fields ...
  "Identities": [ ... meaningful data of user's email etc...],
  "Id": "00000e9b... ",
  "AdditionalData": {
    "extension_05700734c8154786b58d437faf3d30c7_customerId": {
      "ValueKind": 3
    }
  }
}

请问如何修改代码以获取该自定义属性的实际值?


解决方法

方法1:直接从AdditionalData提取值

GraphServiceClient会将未在User类中定义的扩展属性存入AdditionalData字典,直接通过键名取值即可,注意根据实际类型转换:

foreach (var user in result)
{
    var userId = user.Id;
    if (user.AdditionalData.TryGetValue("extension_05700734c8154786b58d437faf3d30c7_customerId", out var customerIdObj))
    {
        // 示例:转换为字符串类型,根据属性实际类型调整
        var customerId = customerIdObj.ToString();
        // 后续业务处理逻辑
    }
}

方法2:使用强类型扩展类

若需要更规范的强类型访问,可创建继承自User的扩展类,将自定义属性作为成员:

public class B2CUser : User
{
    [JsonPropertyName("extension_05700734c8154786b58d437faf3d30c7_customerId")]
    public string CustomerId { get; set; }
}

调用Graph API时指定返回类型:

var result = await graphClient.Users
    .Request()
    .Select("id,Identities,DisplayName,extension_05700734c8154786b58d437faf3d30c7_customerId")
    .Top(999)
    .GetAsync<B2CUser>();

此时可直接通过user.CustomerId访问属性值,序列化后的JSON也会直接显示该属性字段。

方法3:检查权限配置

如果以上方法仍无法获取值,排查Graph API权限是否正确配置:

  • 确保应用已添加User.Read.All或Directory.Read.All权限(根据场景选择委派/应用权限)
  • 已完成权限的管理员同意操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 10:17:23