自定义 Microsoft Graph SDK 服务客户端Customize the Microsoft Graph SDK service client

Microsoft Graph SDK 客户端配置一组默认中间件,以允许 SDK 与 Microsoft Graph 终结点进行通信。The Microsoft Graph SDK client configures a default set of middleware that allows the SDK to communicate with the Microsoft Graph endpoints. 此默认集是可自定义的,允许您更改客户端的行为。This default set is customizable, allowing you to change the behavior of the client. 例如,可以插入自定义日志记录,也可以添加测试处理程序以模拟特定方案。For example, you can insert customized logging, or add a test handler to simulate specific scenarios. 您可以添加和删除中间件组件。You can add and remove middleware components. 需要注意的是,中间件组件运行的顺序非常重要。It is important to note that the order in which middleware components run is significant.

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