Skip to content

Instantly share code, notes, and snippets.

@HenrikFrystykNielsen
Created June 14, 2012 16:38
Show Gist options
  • Save HenrikFrystykNielsen/2931385 to your computer and use it in GitHub Desktop.
Save HenrikFrystykNielsen/2931385 to your computer and use it in GitHub Desktop.
Sample HttpMessageHandler doing async retrieval using .NET 4.5
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace SelfHost.MessageHandlers
{
/// <summary>
/// This sample HttpMessageHandler illustrates how to perform an async operation as part of the
/// HTTP message handler pipeline using the async and await keywords from .NET 4.5
/// </summary>
public class SampleHandler : DelegatingHandler
{
private HttpClient _client;
private Uri _address;
public SampleHandler(Uri address)
{
if (address == null)
{
throw new ArgumentNullException("address");
}
if (!address.IsAbsoluteUri)
{
throw new ArgumentException("Value must be an absolute URI", "address");
}
_address = address;
_client = new HttpClient();
}
/// <summary>
/// We mark the SendAsync with 'async' so that we can await tasks without blocking in the method body.
/// </summary>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Here I can inspect the request and do any pre-processing
// Submit intermediate request and await response
HttpResponseMessage intermediateResponse = await _client.GetAsync(_address);
// If intermediate response is not successful then return a 500 status code
if (!intermediateResponse.IsSuccessStatusCode)
{
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
// Read intermediate response
byte[] intermediateContent = await intermediateResponse.Content.ReadAsByteArrayAsync();
// Now continue with the original request
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
// Here I can inspect the response and do any post-processing
return response;
}
}
}
@bassam
Copy link

bassam commented Mar 13, 2013

Is it safe to re-transfer a request multiple times? Does that depend of the kind of content in the request?

@nibro7778
Copy link

Thanks for your simple example. I want to implement same functionality into MVC project without using Owin, my understanding is that DelegatingHandlers are only invoked for API routes.

My requirement is whenever a new request comes I need to validate for specific request header and if that header is not in the request header then I will add that header to request header with a default value. I have achieved this functionality in WEB API project using DelegatingHandlers but couldn't able to find solution same for MVC project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment