Last active
August 5, 2021 15:49
-
-
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
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
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