Microsoft Graph SDK サービス クライアントをカスタマイズする

Microsoft Graph SDK クライアントは、SDK が Microsoft Graph エンドポイントと通信できるようにするミドルウェアの既定のセットを構成します。 このカスタマイズ可能な既定のセットを使用すると、クライアントの動作を変更できます。 たとえば、カスタマイズされたログやテスト ハンドラーを挿入して、特定のシナリオをシミュレートできます。 ミドルウェア コンポーネントを追加および削除できます。 ミドルウェア コンポーネントの実行順序が重要であることに注意してください。

// tokenCredential is one of the credential classes from Azure.Identity
// scopes is an array of permission scope strings
var authProvider = new AzureIdentityAuthenticationProvider(tokenCredential, scopes: scopes);

var handlers = GraphClientFactory.CreateDefaultHandlers();

// Remove a default handler
// Microsoft.Kiota.Http.HttpClientLibrary.Middleware.CompressionHandler
var compressionHandler =
    handlers.Where(h => h is CompressionHandler).FirstOrDefault();
handlers.Remove(compressionHandler);

// Add a new one
// ChaosHandler simulates random server failures
// Microsoft.Kiota.Http.HttpClientLibrary.Middleware.ChaosHandler
handlers.Add(new ChaosHandler());

var httpClient = GraphClientFactory.Create(handlers);
var customGraphClient = new GraphServiceClient(httpClient, authProvider);

クライアントの HTTP プロキシの構成

一部の環境では、パブリック インターネットにアクセスする前にクライアント アプリケーションで HTTP プロキシを使用する必要があります。 このセクションでは、Microsoft Graph SDK のプロキシを構成する方法について説明します。

// URI to proxy
var proxyAddress = "http://localhost:8888";

// Create an HttpClientHandler with the proxy to
// pass to the Azure.Identity token credential
var handler = new HttpClientHandler
{
    Proxy = new WebProxy(proxyAddress),
};

// Create an options object that corresponds to the
// token credential being used. For example, this sample
// uses a ClientSecretCredential, so the corresponding
// options object is ClientSecretCredentialOptions
var options = new ClientSecretCredentialOptions()
{
    Transport = new HttpClientTransport(handler),
};

var tokenCredential = new ClientSecretCredential(
    "YOUR_TENANT_ID",
    "YOUR_CLIENT_ID",
    "YOUR_CLIENT_SECRET",
    options);

// NOTE: Authentication requests will not go through the proxy.
// Azure.Identity token credential classes have their own separate method
// for configuring a proxy using TokenCredentialOptions.Transport
var authProvider = new AzureIdentityAuthenticationProvider(tokenCredential, scopes);

// This example works with Microsoft.Graph 5+
// Use the GraphClientFactory to create an HttpClient with the proxy
var httpClient = GraphClientFactory.Create(proxy: new WebProxy(proxyAddress));
var graphClient = new GraphServiceClient(httpClient, authProvider);