Created
June 14, 2012 16:38
-
-
Save HenrikFrystykNielsen/2931385 to your computer and use it in GitHub Desktop.
Sample HttpMessageHandler doing async retrieval using .NET 4.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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