C#中新版Microsoft Graph替代.Request()访问Azure AD B2C用户咨询
新版Microsoft Graph SDK替代
.Request()方法的方案 问题背景
旧版基于Microsoft.Graph.Beta的应用通过.Request()方法实现Azure AD B2C用户的查看与搜索,迁移至新版5.52.0 Microsoft Graph SDK(搭配Azure.Identity)时,因.Request()方法被弃用导致报错,需找到替代方案。
新版SDK核心变化
新版Microsoft Graph SDK(v5及以上)采用更简洁的fluent API设计,不再需要.Request()方法,所有查询操作直接通过graphClient.Users链式调用相关方法即可完成。
迁移后的代码实现
以下是对旧版ListUsers功能完整适配的新版代码:
public static async Task ListUsers(GraphServiceClient graphClient) { Console.WriteLine("Getting list of users..."); // 获取一页用户并指定返回字段,替代旧版.Request().Select()逻辑 var result = await graphClient.Users .GetAsync(requestConfiguration => { requestConfiguration.QueryParameters.Select = new[] { "displayName", "id", "identities", "businessPhones" }; }); var users = result.Value; if (users == null || !users.Any()) { Console.WriteLine("No users found."); return; } // 计算字段最大长度,逻辑与旧版一致 int maxDisplayNameLength = users.Max(u => u.DisplayName?.Length ?? 0); int maxIdLength = users.Max(u => u.Id.Length); int maxEmailLength = users .Where(u => u.Identities?.Any(i => i.SignInType == "emailAddress") == true) .Select(u => u.Identities.FirstOrDefault(i => i.SignInType == "emailAddress")?.IssuerAssignedId) .Where(email => !string.IsNullOrEmpty(email)) .Max(email => email.Length); bool isFirst = true; foreach (var user in users) { string email = user.Identities?.FirstOrDefault(i => i.SignInType == "emailAddress")?.IssuerAssignedId; if (string.IsNullOrEmpty(email)) continue; string phoneNumbers = user.BusinessPhones != null ? string.Join(", ", user.BusinessPhones) : string.Empty; if (isFirst) { Console.WriteLine("------------------------"); isFirst = false; } // 格式化输出,逻辑与旧版一致 Console.WriteLine($"DisplayName: {user.DisplayName?.PadRight(maxDisplayNameLength) ?? string.Empty}"); Console.WriteLine($"Id: {user.Id.PadRight(maxIdLength)}"); Console.WriteLine($"Email: {email.PadRight(maxEmailLength)}"); Console.WriteLine($"Phone Numbers: {phoneNumbers}"); Console.WriteLine("------------------------"); } }
关键替换点说明
- 移除
.Request():直接对graphClient.Users调用.GetAsync(),通过requestConfiguration参数配置查询选项 - 字段选择:通过
requestConfiguration.QueryParameters.Select指定返回字段,替代旧版的.Select(e => new { ... }) - 结果获取:新版
.GetAsync()返回UserCollectionResponse,通过.Value属性获取用户列表,替代旧版的result.CurrentPage - 空值处理:新版SDK对可空字段返回更严格,需增加空值判断避免空引用异常
搭配Azure.Identity的调用示例
static async Task Main(string[] args) { var scopes = new[] { "https://graph.microsoft.com/.default" }; var tenantId = "你的B2C租户ID"; var clientId = "你的应用客户端ID"; var clientSecret = "你的应用客户端密钥"; var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret); var graphClient = new GraphServiceClient(clientSecretCredential, scopes); await ListUsers(graphClient); }
内容的提问来源于stack exchange,提问作者ThomasLDev
相关产品推荐
相关产品推荐

