自定义 Microsoft Graph SDK 服务客户端

Microsoft Graph SDK 客户端配置一组默认的中间件,允许 SDK 与 Microsoft Graph终结点通信。 此默认集是可自定义的,允许您更改客户端的行为。 例如,可以插入自定义日志记录,或添加测试处理程序以模拟特定方案。 可以添加和删除中间件组件。 需要注意的是,中间件组件的运行顺序非常重要。

var handlers = GraphClientFactory.CreateDefaultHandlers(authProvider);

// Remove a default handler
var compressionHandler =
    handlers.Where(h => h is CompressionHandler).FirstOrDefault();
handlers.Remove(compressionHandler);

// Add a new one
// ChaosHandler simulates random server failures
handlers.Add(new ChaosHandler());

var httpClient = GraphClientFactory.Create(handlers);

var customGraphClient = new GraphServiceClient(httpClient);

var messages = await customGraphClient.Me.Messages.Request()
    .Top(100)
    .Select(m => m.Subject)
    .GetAsync();

为客户端配置 HTTP 代理

某些环境要求客户端应用程序在可以访问公共 Internet 之前使用 HTTP 代理。 本部分演示如何为 Microsoft Graph SDK 配置代理。

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

// Create a new System.Net.Http.HttpClientHandler with the proxy
var handler = new HttpClientHandler
{
    // Create a new System.Net.WebProxy
    // See WebProxy documentation for scenarios requiring
    // authentication to the proxy
    Proxy = new WebProxy(new Uri(proxyAddress))
};

// Create an options object for the credential being used
// For example, here we're using a ClientSecretCredential so
// we create a ClientSecretCredentialOptions object
var options = new ClientSecretCredentialOptions
{
    // Create a new Azure.Core.HttpClientTransport
    Transport = new HttpClientTransport(handler)
};

var credential = new ClientSecretCredential(
    "YOUR_TENANT_ID",
    "YOUR_CLIENT_ID",
    "YOUR_CLIENT_SECRET",
    options
);

var scopes = new[] { "https://graph.microsoft.com/.default" };

// This example works with Microsoft.Graph 4+
var httpClient = GraphClientFactory.Create(new TokenCredentialAuthProvider(credential, scopes), proxy: new WebProxy(new Uri(proxyAddress)));

GraphServiceClient graphClient = new(httpClient);

/* For Microsoft.Graph version < 4, you'll need to implement an authHandler. Please note
/* that Microsoft.Graph.Auth is deemphasized and will not leave the preview state.

var httpProvider = new HttpProvider(handler, true);
GraphServiceClient graphClient = new(authHandler, httpProvider);

*/