ASP.NET Web API JSON Batch Handler

Batch support is certainly not new to ASP.NET Web API. In fact, it was introduced a couple of years ago.

Recently I was working on a Web API for a mobile application, and I needed batch support using JSON instead of the Multi-part handler which comes built-in to ASP.NET.

I stumbled upon various examples on the web such as the great discussion in this thread. This was the basis for the solution that I put together.

The JSON Batch Handler allows you to send a batch request in a JSON format, so you can pack several requests together. The handler automatically copies the headers from the main request.

 
// Add the headers
foreach (var item in request.Headers)
{
   req.Headers.Add(item.Key, item.Value);
}

It also allows you to assign the content of your message. This was one of the requirements that I had, as I needed to pass on the object to be created on the server.

 
// Add the body
if (r.body != null)
{
   var content = new StringContent(r.body.ToString(), Encoding.UTF8, ApplicationJsonContentType);
   req.Content = content;
}

In essence, the handler processes the main requests and loops through the requests to be created

 
public override async Task ParseBatchRequestsAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}

var jsonSubRequests = await request.Content.ReadAsAsync<JsonRequestMessage[]>(cancellationToken);

// Creating simple requests, and check for the body
var subRequests = jsonSubRequests.Select(r =>
{
var subRequestUri = new Uri(request.RequestUri, "/" + r.relativeUrl);
var req = new HttpRequestMessage(new HttpMethod(r.method), subRequestUri);

// Add the body
if (r.body != null)
{
var content = new StringContent(r.body.ToString(), Encoding.UTF8, ApplicationJsonContentType);
req.Content = content;
}

// Add the headers
foreach (var item in request.Headers)
{
req.Headers.Add(item.Key, item.Value);
}

req.CopyBatchRequestProperties(request);

return req;
});

return subRequests.ToList();
}

You can test the batch operation in real time using a tool such as Postman:

Batch test result

You can check out the complete source code with the tests in this repo.

I hope you find it as helpful as I did.

No Comments Yet.

Leave a Reply

Your email address will not be published. Required fields are marked *