使用英语阅读

通过


自定义 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, 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);

为客户端配置 HTTP 代理

某些环境要求客户端应用程序在访问公共 Internet 之前使用 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, 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);