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

a 夏天 提交于 2019-12-04 10:12:15

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.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!