Sometimes, you have little/no control of the code you are writing tests for. If it's already been designed to use HttpContext.Current
, and you keep getting "Operation is not supported on this platform."
errors like i struggled with, this will help.
public static class NameValueCollectionExtensions
{
public static NameValueCollection AddValue(this NameValueCollection headers, string key, string value)
{
Type t = headers.GetType();
t.InvokeMember("MakeReadWrite", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, null);
t.InvokeMember("InvalidateCachedArrays", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, null);
t.InvokeMember("BaseAdd", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, new object[] { key, new System.Collections.ArrayList() { value } });
t.InvokeMember("MakeReadOnly", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, null);
return headers;
}
}
With that class in the same namespace, you can add the headers like:
HttpContext.Current.Request.Headers.AddValue("header_key", "header_value");
Of course, if you don't like extension methods, you could always use a wrapper method instead.
I hope this helps someone.