How to Modify HTTP Header of a request using C#?

2019-04-10 17:15发布

问题:

I was trying to modify a HTTP Header using C#. I tried to manipulate the Request.Headers on Page preinit event. But when i try to set anything to the Headers, i get PlatformNotSupportedException. Since We can not set a new NameValueCollection to Reqeust.Headers, I tried to set the value using following code:

Request.Headers.Set(HttpRequestHeader.UserAgent.ToString(), "some value");

Any idea how can this be achieved?

回答1:

Try this:

HttpContext.Current.Request.Headers["User-Agent"] = "Some Value";

EDIT: This could be your reason: http://bigjimindc.blogspot.com/2007/07/ms-kb928365-aspnet-requestheadersadd.html

There is a code snippet in that, which adds a new header to the Request.Headers. Verified on Windows 7 32 bit OS too.

But you might want to replace the line:

HttpApplication objApp = (HttpApplication)r_objSender;

with:

HttpApplication objApp = (HttpApplication)HttpContext.Current.ApplicationInstance;

EDIT: To replace the existing Header value, use:

t.InvokeMember("BaseSet", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, new object[] { "Host", item });

where "Host" is a Header name.



回答2:

Adding the complete (working) code from the linked blog - incase that blog vanishes

HttpApplication objApp = (HttpApplication)HttpContext.Current.ApplicationInstance;
HttpRequest Request = (HttpContext)objApp.Context.Request;

//get a reference
NameValueCollection headers = Request.Headers;

//get a type
Type t = headers.GetType();
System.Collections.ArrayList item = new System.Collections.ArrayList();

t.InvokeMember("MakeReadWrite",BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,null,headers,null);
t.InvokeMember("InvalidateCachedArrays",BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,null,headers,null);
item.Add("CUSTOM_HEADER_VALUE");
t.InvokeMember("BaseAdd",BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,null,headers, new object[]{"CUSTOM_HEADER_NAME",item});
t.InvokeMember("MakeReadOnly",BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,null,headers,null);