2

我有一个删除多个事件的方法。目前代码如下:

    public async Task DeleteEvents(IEnumerable<string> eventExternalIds)
    {
        foreach(var eventExternalId in eventExternalIds)
        {
            await DeleteEvent(eventExternalId);
        }
    }

    public async Task DeleteEvent(string eventExternalId)
    {
        await GraphClient
            .Users[Username]
            .Calendars[CalendarName]
            .Events[eventExternalId]
            .Request()
            .DeleteAsync();
    }

我想它不会在删除任何大量 id 时表现良好。有没有办法批量删除它们而不是单独删除它们?

4

1 回答 1

5

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的支持

于 2019-06-17T22:39:37.213 回答