使用Microsoft.Graph.GraphServiceClient如何仅返回指定用户属性?
解决Azure AD B2C通过Microsoft Graph仅获取指定用户属性的问题
问题原因
你遇到的情况是因为Microsoft Graph .NET SDK的默认序列化行为:SDK使用的User实体类包含用户对象的所有属性,当调用.Select("id")时,Graph API确实只返回了id属性,但SDK会把User类中未返回的其他属性设为null,最终序列化整个对象时,这些null属性也会被输出。
解决方案
以下几种方法可以实现仅返回指定属性(如id):
方法1:使用动态类型接收响应
放弃强类型的User类,改用dynamic类型接收API返回内容,仅保留实际返回的属性:
var response = await graphClient.Users .Request() .Select("id") .GetAsync(); var userIds = new List<string>(); foreach (dynamic user in response) { userIds.Add(user.id); // 序列化单个用户时,只会包含id属性 Console.WriteLine(JsonSerializer.Serialize(user)); }
方法2:自定义DTO类并映射
创建仅包含所需属性的DTO类,将SDK返回的User对象映射到该DTO:
// 自定义DTO public class UserIdDto { public string Id { get; set; } } // 请求并映射 var users = await graphClient.Users .Request() .Select("id") .GetAsync(); var userIds = users.Select(u => new UserIdDto { Id = u.Id }).ToList(); Console.WriteLine(JsonSerializer.Serialize(userIds));
方法3:直接调用原生HTTP请求
绕开SDK的实体类封装,直接发送HTTP请求并处理原始JSON响应,精准控制返回内容:
var httpClient = new HttpClient(); // 获取访问令牌 var tokenRequest = new HttpRequestMessage(HttpMethod.Post, $"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"); tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string> { ["client_id"] = client_id, ["client_secret"] = client_secret, ["scope"] = "https://graph.microsoft.com/.default", ["grant_type"] = "client_credentials" }); var tokenResponse = await httpClient.SendAsync(tokenRequest); var tokenContent = await tokenResponse.Content.ReadFromJsonAsync<Dictionary<string, string>>(); var accessToken = tokenContent["access_token"]; // 发送获取用户id的请求 var userRequest = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users?$select=id"); userRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var userResponse = await httpClient.SendAsync(userRequest); var userContent = await userResponse.Content.ReadAsStringAsync(); Console.WriteLine(userContent);
补充说明
- 你可以通过抓包工具验证:调用
.Select("id")时,Graph API本身确实只返回了id属性,问题出在SDK的实体类序列化环节。 - 若仅需收集用户id列表,方法1和方法2足够简洁;若需完全控制返回的JSON结构,方法3更直接。
内容的提问来源于stack exchange,提问作者bdcoder
相关产品推荐
相关产品推荐

