如何在C#中使用Graph API更新用户头像
使用C#通过Microsoft Graph API更新用户头像
所需权限说明
- 更新本人头像:需要
Delegated类型的User.ReadWrite权限 - 更新其他用户头像:需要
Application类型的User.ReadWrite.All权限,或Delegated类型的User.ReadWrite.All权限(需管理员同意)
安装依赖包
通过NuGet安装以下包:
Microsoft.Graph:Graph API核心SDKMicrosoft.Identity.Client:用于身份验证(根据你的认证方式选择)
代码实现
1. 初始化Graph服务客户端
根据权限类型创建GraphServiceClient实例:
场景A:使用Application权限(批量更新其他用户)
using Microsoft.Graph; using Microsoft.Identity.Client; var clientId = "你的Azure应用Client ID"; var tenantId = "你的租户ID"; var clientSecret = "你的应用客户端密钥"; var scopes = new[] { "https://graph.microsoft.com/.default" }; var confidentialClient = ConfidentialClientApplicationBuilder .Create(clientId) .WithTenantId(tenantId) .WithClientSecret(clientSecret) .Build(); var authProvider = new ClientCredentialProvider(confidentialClient, scopes); var graphClient = new GraphServiceClient(authProvider);
场景B:使用Delegated权限(更新本人或授权范围内的其他用户)
using Microsoft.Graph; using Microsoft.Identity.Client; var clientId = "你的Azure应用Client ID"; var tenantId = "common"; // 或指定租户ID var redirectUri = "http://localhost"; // 应用注册中配置的重定向URI var scopes = new[] { "User.ReadWrite", "User.ReadWrite.All" }; var publicClient = PublicClientApplicationBuilder .Create(clientId) .WithTenantId(tenantId) .WithRedirectUri(redirectUri) .Build(); var authResult = await publicClient.AcquireTokenInteractive(scopes).ExecuteAsync(); var authProvider = new DelegateAuthenticationProvider(requestMessage => { requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken); return Task.CompletedTask; }); var graphClient = new GraphServiceClient(authProvider);
2. 更新用户头像
更新本人头像
public async Task UpdateMyProfilePicture(GraphServiceClient graphClient, string imagePath) { using var imageStream = new FileStream(imagePath, FileMode.Open); await graphClient.Me.Photo.Content.PutAsync(imageStream); }
更新指定其他用户头像
public async Task UpdateUserProfilePicture(GraphServiceClient graphClient, string userId, string imagePath) { using var imageStream = new FileStream(imagePath, FileMode.Open); // userId可以是用户ID或用户UPN(如user@domain.com) await graphClient.Users[userId].Photo.Content.PutAsync(imageStream); }
关键注意事项
- 图片要求:必须为JPEG格式,文件大小不超过4MB,建议使用48x48、96x96、240x240等标准尺寸
- 头像更新后可能存在缓存延迟,最长需要几分钟才能在所有Microsoft服务中同步显示
- 如果用户原本无头像,调用API会自动创建;已有头像则直接覆盖
内容的提问来源于stack exchange,提问作者Ashish Prajapati
相关产品推荐
相关产品推荐

