在C#中通过Graph API获取Microsoft个人资料图片,可以按照以下步骤进行:
using Microsoft.Identity.Client;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string clientId = "YourClientId";
string clientSecret = "YourClientSecret";
string tenantId = "YourTenantId";
string graphApiEndpoint = "https://graph.microsoft.com/v1.0/me/photo/$value";
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}")
.Build();
var scopes = new[] { "User.Read" };
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
var response = await httpClient.GetAsync(graphApiEndpoint);
if (response.IsSuccessStatusCode)
{
// 处理获取到的个人资料图片
var imageBytes = await response.Content.ReadAsByteArrayAsync();
// ...
}
else
{
Console.WriteLine($"请求失败: {response.StatusCode}");
}
}
}
}
请注意,上述代码中的"YourClientId"、"YourClientSecret"和"YourTenantId"需要替换为你在Azure门户中创建的应用程序注册的相关信息。
这样,你就可以通过Graph API获取Microsoft个人资料图片了。
领取专属 10元无门槛券
手把手带您无忧上云