Skip to content

Instantly share code, notes, and snippets.

@timiles
Last active August 5, 2021 15:49
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save timiles/4445456 to your computer and use it in GitHub Desktop.
Save timiles/4445456 to your computer and use it in GitHub Desktop.
Mock HttpContext.Current.Request.Headers. This is ugly but it works. credit: http://bigjimindc.blogspot.co.uk/2007/07/ms-kb928365-aspnet-requestheadersadd.html
HttpContext.Current = new HttpContext(
new HttpRequest("", "http://tempuri.org", ""), new HttpResponse(new StringWriter()));
NameValueCollection headers = HttpContext.Current.Request.Headers;
Type t = headers.GetType();
const BindingFlags nonPublicInstanceMethod = BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance;
t.InvokeMember("MakeReadWrite", nonPublicInstanceMethod, null, headers, null);
t.InvokeMember("InvalidateCachedArrays", nonPublicInstanceMethod, null, headers, null);
// eg. add Basic Authorization header
t.InvokeMember("BaseRemove", nonPublicInstanceMethod, null, headers, new object[] { "Authorization" });
t.InvokeMember("BaseAdd", nonPublicInstanceMethod, null, headers,
new object[] { "Authorization", new ArrayList{"Basic " + api_key} });
t.InvokeMember("MakeReadOnly", nonPublicInstanceMethod, null, headers, null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment