C#如何使用Microsoft Graph API获取Office 365用户照片

9

我希望能够在Azure活动目录中获取所有用户的office365照片。

目前,我可以使用Graph SDK获取当前用户的电子邮件。

GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();

public async Task<string> GetMyEmailAddress(GraphServiceClient graphClient)
    {          
        User me = await graphClient.Me.Request().Select("mail,userPrincipalName").GetAsync();
        return me.Mail ?? me.UserPrincipalName;
    }

但是我不确定如何将来自https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/profilephoto_get获取照片部分集成到代码中。

非常感谢提供任何帮助或者示例代码!

4个回答

10

这有助于获取图片

 GraphServiceClient graphServiceClient = GetAuthenticatedGraphServiceClient();

 Stream photo = await graphServiceClient.Me.Photo.Content.Request().GetAsync();

 if (photo != null)
 {
     MemoryStream ms = new MemoryStream();
     photo.CopyTo(ms);
     byte[] buffer = ms.ToArray();
     string result = Convert.ToBase64String(buffer);
     string imgDataURL = string.Format("data:image/png;base64,{0}", result);
     ViewBag.ImageData = imgDataURL;
 }
 else
 {
      ViewBag.ImageData = "";
 }

enter image description here


4

在2021年,您只需要执行以下操作:

Stream photo = await graphServiceClient.Me.Photo.Content.Request().GetAsync();
            ViewData["Photo"] = Convert.ToBase64String((photo as MemoryStream).ToArray());

然后在你的HTML中:

<img src="data:image/png;base64, @ViewData["Photo"]" />

1
您可以使用 graphClient.Me.Photo.Content 获取照片,它将以流的形式检索照片的二进制数据:
 public async Task GetPictureAsync()
 {
     GraphServiceClient graphClient = GetGraphServiceClient();

     var photo = await graphClient.Me.Photo.Content.Request().GetAsync();
     using (var fileStream = File.Create("C:\\temp\\photo.jpg"))
     {
         photo.Seek(0, SeekOrigin.Begin);
         photo.CopyTo(fileStream);
     }
 }

如果我的应用程序在Azure AD端点中注册,我是否仍然可以使用Microsoft Graph API?因为现在我收到了错误提示,说我的应用程序不支持此API版本。 - yfan183
1
是的。我已经用我在Azure门户中注册的应用程序进行了上述代码的测试,var photo = await graphClient.Me.Photo.Content.Request().GetAsync();这一行请求v1.0 MS Graph API (https://graph.microsoft.com/v1.0/me/photo/$value)。 - RasmusW
2
当我尝试使用“await graphClient.Users["userAddress@email.com"].Photo.Content.Request().GetAsync();”来访问用户照片时,我收到了一个奇怪的错误提示:“Access Denied: Check Credentials and try again”。然而,我可以使用“await graphClient.Users["userAddress@email.com"].Request().Select("mail").GetAsync();"来获取用户的电子邮件等其他信息。 - yfan183

-1

这个页面也有一些不错的帮助:https://developer.microsoft.com/zh-cn/graph/docs/concepts/uwp - Felix Andrew MSFT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接