Customize the Microsoft Graph SDK service client

The Microsoft Graph SDK client configures a default set of middleware that allows the SDK to communicate with the Microsoft Graph endpoints. This customizable default set allows you to change the client's behavior. For example, you can insert customized logging or a test handler to simulate specific scenarios. You can add and remove middleware components. It's important to note that the order in which middleware components run is significant.

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

Configuring the HTTP proxy for the client

Some environments require client applications to use an HTTP proxy before accessing the public internet. This section shows how to configure the proxy for the Microsoft Graph SDKs.

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

var authProvider = new AzureIdentityAuthenticationProvider(tokenCredential, scopes);

// This example works with Microsoft.Graph 5+
var httpClient = GraphClientFactory.Create(proxy: new WebProxy(new Uri(proxyAddress)));
var graphClient = new GraphServiceClient(httpClient, authProvider);