如何使用 C# 中的 Graph API 使用 UPN(用户主体名称)更新用户个人资料照片

问题描述 投票:0回答:1

我尝试使用 UserID ,效果很完美,但是当我尝试使用 userPrincipalName 时,它不起作用。

public async Task<bool> UpdateProfilePicture(string userId, string imagePath)
{
    try
    {
        using (var stream = new FileStream(imagePath, FileMode.Open))
        {
            await GraphClient.Users[userId].Photo.Content.PutAsync(stream);
            Console.WriteLine("Profile picture updated successfully.");
            return true;
        }
    }
    catch (ODataError odataError)
    {
        Console.WriteLine($"OData error details:");
        Console.WriteLine($"Code: {odataError.Error?.Code}");
        Console.WriteLine($"Message: {odataError.Error?.Message}");
        throw;
    }
    catch (ServiceException ex)
    {
        Console.WriteLine($"Error updating profile picture: {ex.Message}");
        return false;
    }
}

如果我尝试使用 userPrincipalName 那么它不起作用。

c# .net-core azure-active-directory azure-web-app-service
1个回答
0
投票

最初我遇到了同样的错误

enter image description here

要解决更新用户个人资料照片的错误,您需要通过传递以下代码片段通过 UPN 获取用户:

Var user = await GraphClient.Users[userPrincipalName].GetAsync();

要通过UPN更新用户的个人资料图片,请修改如下代码:

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models.ODataErrors;

namespace UserProperties
{
    public class GraphHandler
    {
        public GraphServiceClient GraphClient { get; set; }

        public GraphHandler()
        {
            var tenantId = "XXX";
            var clientId = "XXX";
            var clientSecret = "XXX";
            GraphClient = CreateGraphClient(tenantId, clientId, clientSecret);
        }

        public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
        {
            var options = new TokenCredentialOptions
            {
                AuthorityHost = Azure.Identity.AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new Azure.Identity.ClientSecretCredential(tenantId, clientId, clientSecret, options);
            var scopes = new[] { "https://graph.microsoft.com/.default" };

            return new GraphServiceClient(clientSecretCredential, scopes);
        }

        public async Task<bool> UpdateProfilePictureByUPN(string userPrincipalName, string imagePath)
        {
            try
            {
                using (var stream = new FileStream(imagePath, FileMode.Open))
                {
                    // Get user by UPN
                    var user = await GraphClient.Users[userPrincipalName].GetAsync();
                    if (user != null)
                    {
                        // Update profile picture
                        await GraphClient.Users[user.Id].Photo.Content.PutAsync(stream);
                        Console.WriteLine("Profile picture updated successfully.");
                        return true;
                    }
                    else
                    {
                        Console.WriteLine($"User with UPN '{userPrincipalName}' not found.");
                        return false;
                    }
                }
            }
            catch (ODataError odataError)
            {
                Console.WriteLine($"OData error details:");
                Console.WriteLine($"Code: {odataError.Error?.Code}");
                Console.WriteLine($"Message: {odataError.Error?.Message}");
                throw;
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error updating profile picture: {ex.Message}");
                return false;
            }
        }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var handler = new GraphHandler();
            var userPrincipalName = "[email protected]"; // Replace with the desired user's UPN
            await handler.UpdateProfilePictureByUPN(userPrincipalName, "C:\\Users\\rukmini\\Downloads\\ruk.jpg");
        }
    }
}

enter image description here

头像更新成功如下:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.