Created
February 15, 2012 10:28
-
-
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...
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.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