Partilhar via


Personalizar o cliente do serviço SDK do Microsoft Graph

O cliente do SDK do Microsoft Graph configura um conjunto predefinido de middleware que permite ao SDK comunicar com os pontos finais do Microsoft Graph. Este conjunto predefinido personalizável permite-lhe alterar o comportamento do cliente. Por exemplo, pode inserir registos personalizados ou um processador de teste para simular cenários específicos. Pode adicionar e remover componentes de middleware. É importante ter em atenção que a ordem pela qual os componentes de 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, isCaeEnabled: true, scopes: scopes);

var handlers = GraphClientFactory.CreateDefaultHandlers();

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

Configurar o proxy HTTP para o cliente

Alguns ambientes exigem que as aplicações cliente utilizem um proxy HTTP antes de acederem à Internet pública. Esta secçã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, isCaeEnabled: true, scopes: 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);