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

独自空忆成欢 提交于 2019-12-06 04:17:46

问题


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);


来源:https://stackoverflow.com/questions/3975240/how-to-modify-http-header-of-a-request-using-c

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