msgraph-sdk-dotnet v1.15.0 或以上
对于msgraph-sdk-dotnet
版本1.15.0
或更高版本, 已通过BatchRequestContent
类引入了对 Batch 请求的支持
例子
//1. construct a Batch request
var batchRequestContent = new BatchRequestContent();
var step = 1;
foreach (var eventId in eventIds)
{
var requestUrl = graphClient
.Me
.Events[eventId]
.Request().RequestUrl;
var request = new HttpRequestMessage(HttpMethod.Delete, requestUrl);
var requestStep = new BatchRequestStep(step.ToString(), request, null);
batchRequestContent.AddBatchRequestStep(requestStep);
step++;
}
//2. Submit request
var batchRequest = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/v1.0/$batch");
batchRequest.Content = batchRequestContent;
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(batchRequest);
var httpClient = new HttpClient();
var batchResponse = await httpClient.SendAsync(batchRequest);
//3. Process response
var batchResponseContent = new BatchResponseContent(batchResponse);
var responses = await batchResponseContent.GetResponsesAsync();
foreach (var response in responses)
{
if (response.Value.IsSuccessStatusCode)
{
//...
}
}
问题
- 虽然可能会出现定位
NetCore 2.1
或以上或.NET Framework
NullReferenceException
异常,但要解决此问题,您可以切换到1.16.0-preview.1
(详细信息)
限制
注意:一个批次不能容纳超过 20 个请求
msgraph-sdk-dotnet v1.14.0 或更早版本
对于以前的版本,以下示例演示了如何实现对 Batch 请求的支持:
var batchRequest = new BatchRequest();
foreach (var eventId in eventIds)
{
var request = graphClient.Me.Events[eventId].Request();
batchRequest.AddQuery(request,HttpMethod.Delete);
}
var responses = await graphClient.SendBatchAsync(batchRequest);
哪里BatchRequest
是一个自定义类,它增加了对JSON Batching的支持