views:

32

answers:

1

Hi,

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?

+2  A: 

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.

Kay
I get PlatformNotSupportedException. I use Windows 7 32 Bit with IIS 7.5
Amit
@Amit: Which .Net framework do you use?
Kay
I used the above code on Win Server 2008, IIS 7, .Net Framework 3.5 SP1; and it worked nicely
Kay
@Amit: Use the EDIT version, this will work for you
Kay
@Kay: Thanks a lot.. :)
Amit