将照片从Microsoft Graph Client SDK转换为Base64String

时间:2019-04-29 01:35:20

标签: c# microsoft-graph

我正在使用对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对象上不可用,我有点迷茫。

1 个答案:

答案 0 :(得分:2)

由于Get photo endpointmsgraph-sdk-dotnet仅支持将照片内容作为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();
    }
}