Skip to content

Instantly share code, notes, and snippets.

@bittercoder
Created February 15, 2012 10:28
Show Gist options
  • Save bittercoder/1834915 to your computer and use it in GitHub Desktop.
Save bittercoder/1834915 to your computer and use it in GitHub Desktop.
A really hacky way to grab the HttpContext from the request of a WCF Web API DelegatingHandler...
using System;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace Ugh {
public static class HttpRequestMessageExtensions
{
static FieldInfo _currentThreadDataField;
static FieldInfo _httpContextField;
public static HttpContext GetHttpContext(this HttpRequestMessage request)
{
var webHost = request.Properties["webhost"];
if (webHost==null) throw new Exception("Request does not contain webHost property");
if (_currentThreadDataField == null)
{
_currentThreadDataField = webHost.GetType().GetField("currentThreadData", BindingFlags.NonPublic | BindingFlags.Instance);
if (_currentThreadDataField == null)
{
throw new Exception("webHost does not contain currentThreadData field");
}
}
var currentThreadData = _currentThreadDataField.GetValue(webHost);
if (_httpContextField == null)
{
_httpContextField = currentThreadData.GetType().GetField("httpContext", BindingFlags.NonPublic | BindingFlags.Instance);
if (_httpContextField == null)
{
throw new Exception("currentThreadData does not contain httpContext field");
}
}
return (HttpContext)_httpContextField.GetValue(currentThreadData);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment