Anpassen des Microsoft Graph SDK-Dienstclients

Der Microsoft Graph SDK-Client konfiguriert einen Standardsatz von Middleware, der es dem SDK ermöglicht, mit den Microsoft Graph-Endpunkten zu kommunizieren. Mit diesem anpassbaren Standardsatz können Sie das Verhalten des Clients ändern. Sie können beispielsweise eine benutzerdefinierte Protokollierung oder einen Testhandler einfügen, um bestimmte Szenarien zu simulieren. Sie können Middlewarekomponenten hinzufügen und entfernen. Es ist wichtig zu beachten, dass die Reihenfolge, in der Middlewarekomponenten ausgeführt werden, signifikant ist.

// 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);

Konfigurieren des HTTP-Proxys für den Client

In einigen Umgebungen müssen Clientanwendungen vor dem Zugriff auf das öffentliche Internet einen HTTP-Proxy verwenden. In diesem Abschnitt wird gezeigt, wie Sie den Proxy für die Microsoft Graph SDKs konfigurieren.

// 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);