本文介绍了如何修改使用C#的请求的HTTP头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是想用C#来修改HTTP标头。我试图操纵在页面preinit事件Request.Headers。但是,当我尝试任何设置为标题,我得到PlatformNotSupportedException。既然我们不能设置一个新的NameValueCollection到Reqeust.Headers,我尝试使用下面的代码来设置值:

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?

推荐答案

试试这个:

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



编辑:
这可能是你的理由:

有一个代码片断在于,它增加了一个新的头到Request.Headers。 。验证的Windows 7 32位操作系统太

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;



编辑:
要替换现有的标头值,使用

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.

这篇关于如何修改使用C#的请求的HTTP头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:55