How to change HTTP request header using C #?

I tried to change the HTTP header using C #. I tried to manipulate the Preinit event on the Request.Headers page. But when I try to set something in the headers, I get a PlatformNotSupportedException. Since we cannot set the new NameValueCollection in Reqeust.Headers, I tried to set the value using the following code:

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

Any idea how this can be achieved?

+4
source share
2 answers

Try the following:

 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 piece of code in this that adds a new header to Request.Headers. Also tested on 32-bit Windows 7.

But you can 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 the name of the header.

+10
source

Adding full (working) code from a linked blog - if this blog disappears

 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); 
+3
source

All Articles