Microsoft.Graph.ServiceException 尝试下载用户图片时

Microsoft.Graph.ServiceException when trying to download user image

我有一个非常令人沮丧的问题,我想做的就是从 O365 获取用户图像并将它们简单地显示在我的网页上,该网页托管在 Azure azpp 服务上。

正如您从 this SO and this SharePoint.StackExchange 问题中看到的那样,当简单地尝试在 <img> 标签中显示从 SharePoint 获取的 link 时,图像无法加载。

但是,在导航到新选项卡中的图像并刷新我的页面后,iamges 加载正常。 任何人都可以解释这种行为吗?这对我来说毫无意义

无论如何,因为无论出于何种原因,它都不起作用(登录用户显然具有正确的权限,因为图像在导航到它们后会显示), 我想我会尝试使用图表 API 下载图像。

所以我下载了 quick start project 并尝试使用

下载 iamges
public async Task<Stream> TestAsync(GraphServiceClient graphClient)
{
    var users = graphClient.Users;
    var jk = users["user.name@domain.com"];

    return await jk.Photo.Content.Request().GetAsync();
}

但我刚得到

Exception of type 'Microsoft.Graph.ServiceException' was thrown.

然而,当我尝试在 API 图形资源管理器中查看同一图像时,我可以下载该图像。请有人可以帮助我在我的网页中显示 SharePoint 用户图像,而无需用户首先直接导航到图像。为什么这么难?

获得有效令牌后,请确保您的权限范围包括 User.Read.All,例如:

查询:

var user = graphClient.Users["<userPrincipalName>"];

对应以下端点

Url: /users/{userPrincipalName}
Method: GET

需要 User.Read.All 范围,请参阅 permission section 了解更多详情。

另外,如果access without a user token requires Administrative Consent之前可以使用

例子

var users = graphClient.Users;
var user = users[accountName];
var photo = await user.Photo.Content.Request().GetAsync() as MemoryStream;
using (var file = new FileStream("./user.jpg", FileMode.Create, FileAccess.Write))
{
     if (photo != null) photo.WriteTo(file);
}