You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Microsoft Graph获取用户照片出现UnknownError及Stream转Base64问题

问题排查与解决方案

一、UnknownError 错误排查与修复

你的控制器代码存在两个核心错误,直接引发了该异常:

  1. 参数名拼写不匹配:URL传递的参数是userPrincipalName,但控制器方法参数写成了urserPrincipleName(拼写错误),导致无法正确接收参数值。
  2. Graph API路径硬编码错误:代码中Users["{urserPrincipleName}"]是将{urserPrincipleName}作为固定字符串传入Graph API,而非使用变量值,这会请求一个不存在的用户,进而触发错误。

修正后的HomeController.cs代码:

[AuthorizeForScopes(Scopes = new[] { "User.Read.All" })]
public async Task<IActionResult> GetProfilePhoto(string userPrincipalName)
{
    // 使用参数变量替换硬编码字符串
    var photoStream = await _graphServiceClient.Users[userPrincipalName].Photo.Content.Request().GetAsync();

    // 将Stream转换为Base64字符串,传递给视图
    byte[] photoBytes;
    using (var memoryStream = new MemoryStream())
    {
        await photoStream.CopyToAsync(memoryStream);
        photoBytes = memoryStream.ToArray();
    }
    string base64Photo = Convert.ToBase64String(photoBytes);

    return PartialView("_Headshot", base64Photo);
}

二、Stream转Base64展示图片的解决方案

不建议直接在视图中处理Stream对象(易出现流关闭、重复读取等问题),最优方式是在控制器中完成Stream到Base64的转换,将字符串传递给视图。

修正后的_Headshot.cshtml代码:

@model string
<img src="data:image/jpeg;base64, @Model" alt="用户头像" />

额外注意事项

  • 确保_graphServiceClient已正确初始化,且User.Read.All权限已完成配置与授权。
  • 若用户未设置头像,Graph API会返回404错误,建议添加异常处理逻辑:
try
{
    var photoStream = await _graphServiceClient.Users[userPrincipalName].Photo.Content.Request().GetAsync();
    // 转换逻辑...
}
catch (ServiceException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
    // 返回默认头像的Base64字符串或空视图
    return PartialView("_Headshot", "默认头像Base64字符串");
}

内容的提问来源于stack exchange,提问作者s15199d

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 18:05:12