【问题标题】:Convert photo from Microsoft Graph Client SDK to Base64String将照片从 Microsoft Graph 客户端 SDK 转换为 Base64String
【发布时间】:2019-04-30 06:42:32
【问题描述】:

我正在使用对 Microsoft Graph 的 httpClient 调用的旧实现来获取用户的照片。以下代码有效,但我现在使用的是 Graph Client SDK,并且事情的处理方式略有不同。我很难转换代码,因为在线示例和其他参考资料似乎没有相同的方法。

旧代码:

var response = await httpClient.GetAsync($"{webOptions.GraphApiUrl}/beta/me/photo/$value");
byte[] photo = await response.Content.ReadAsByteArrayAsync();
return Convert.ToBase64String(photo);

新代码:

var graphServiceClient = await graphClient.GetAuthenticatedGraphClientAsync(HttpContext);
Stream photo = await graphServiceClient.Me.Photo.Content.Request().GetAsync();

我已经尝试过来自 herehere 的示例,但由于 ReadAsByteArrayAsync() 在新的 photo 对象上不可用,我有点迷茫。

【问题讨论】:

  • 看看下面的帖子:techcommunity.microsoft.com/t5/Microsoft-Graph/…——帖子里的OP,提供了他自己的问题的答案,相信你会在用例的答案中找到代码你正在寻找。答案有一个扩展方法,它调用 GraphAPI 以通过ReadAsStreamAsync() 获取图像,但向调用者返回Task<byte[]>
  • 谢谢,但这是我使用的相同方法。新方法中的返回对象不同。它是一种“流”类型。
  • OPs 问题使用相同的方法,但答案不同并直接处理stream -- 仔细查看代码。

标签: c# microsoft-graph-api


【解决方案1】:

由于msgraph-sdk-dotnet for Get photo endpoint 仅支持将照片内容作为Stream 返回

public interface IProfilePhotoContentRequest : IBaseRequest
{
    /// <summary>Gets the stream.</summary>
    /// <returns>The stream.</returns>
    Task<Stream> GetAsync();

    /// <summary>Gets the stream.</summary>
    /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken" /> for the request.</param>
    /// <param name="completionOption">The <see cref="T:System.Net.Http.HttpCompletionOption" /> to pass to the <see cref="T:Microsoft.Graph.IHttpProvider" /> on send.</param>
    /// <returns>The stream.</returns>
    Task<Stream> GetAsync(
      CancellationToken cancellationToken,
      HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead);

    //...
}

Convert.ToBase64String Method接受一个字节数组,下面的例子演示了如何转换原来的例子:

var graphServiceClient = await graphClient.GetAuthenticatedGraphClientAsync(HttpContext);
var photoStream = await graphServiceClient.Me.Photo.Content.Request().GetAsync();
var photoBytes = ReadAsBytes(photoStream);
var result = Convert.ToBase64String(photoBytes);

在哪里

//Convert Stream to bytes array  
public static byte[] ReadAsBytes(Stream input)
{
    using (var ms = new MemoryStream())
    {
        input.CopyTo(ms);
        return ms.ToArray();
    }
}

【讨论】:

    猜你喜欢
    • 2018-08-10
    • 1970-01-01
    • 2018-06-20
    • 2018-06-09
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多