GraphServiceClient で Content.Request().GetAsync() を2回呼び出すとMicrosoft.Graph.ServiceExceptionが発生する - ASP.NET Core

GraphServiceClient で Content.Request().GetAsync() を2回呼び出すとMicrosoft.Graph.ServiceExceptionが発生する現象について紹介します。

現象の確認

こちらのページのプログラムを実装します。
Content.cshtml.csについて、以下のコードを記述します。
Content.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Graph;

namespace AuthenticationAzureADGetUserinfo.Pages
{
  [Authorize]
  public class ContentModel : PageModel
  {
    private readonly GraphServiceClient _graphServiceClient;

    public string ID { get; set; }
    public string Name { get; set; }
    public string GivenName { get; set; }
    public string Mail { get; set; }
    public string Image { get; set; }

    public ContentModel(GraphServiceClient graphServiceClient)
    {
      _graphServiceClient = graphServiceClient;
    }
    
    public async void OnGet()
    {
      User user = await _graphServiceClient.Me.Request().GetAsync();

      ID = user.Id;
      Name = user.DisplayName;
      GivenName = user.GivenName;
      Mail = user.Mail;

      Stream s = await _graphServiceClient.Me.Photo.Content.Request().GetAsync();
      byte[] photoByte = ((MemoryStream)s).ToArray();
      Image = Convert.ToBase64String(photoByte);
    }
  }
}

プロジェクトを実行し、Azure ADアカウントでサインインし、(アプリケーションルート)/Content URLのページを表示すると、 2回目のContent.Request().GetAsync() の行で以下のエラーが発生します。
Microsoft.Graph.ServiceException
HResult=0x80131500
Message=Code: generalException
Message: An error occurred sending the request.

内部例外 1:
ObjectDisposedException: Cannot access a disposed object.
ObjectDisposed_ObjectName_Name

原因

不明です。
サンプルコードでは動作することになっており、バージョンによっては例外が発生せずに動作するのかもしれません。

対処法

.Request().GetAsync().Request().GetAsync().Result に変更し、await, async を利用しないコードにすると例外発生を回避できます。
OnGetメソッドを以下のコードに書き換えます。

public void OnGet()
{
  User user = _graphServiceClient.Me.Request().GetAsync().Result;
  ID = user.Id;
  Name = user.DisplayName;
  GivenName = user.GivenName;
  Mail = user.Mail;

  Stream s = _graphServiceClient.Me.Photo.Content.Request().GetAsync().Result;
  byte[] photoByte = ((MemoryStream)s).ToArray();
  Image = Convert.ToBase64String(photoByte);
}

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2022-08-08
作成日: 2022-08-08
iPentec all rights reserverd.