Personalizar o cliente de serviço SDK do Microsoft Graph

O cliente SDK do Microsoft Graph configura um conjunto padrão de middleware que permite que o SDK se comunique com os pontos de extremidade do Microsoft Graph. Esse conjunto padrão personalizável permite que você altere o comportamento do cliente. Por exemplo, você pode inserir log personalizado ou um manipulador de teste para simular cenários específicos. Você pode adicionar e remover componentes de middleware. É importante observar que a ordem na qual os componentes do middleware são executados é significativa.

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

Configurando o proxy HTTP para o cliente

Alguns ambientes exigem que os aplicativos cliente usem um proxy HTTP antes de acessar a Internet pública. Esta seção mostra como configurar o proxy para os SDKs do Microsoft Graph.

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