【问题标题】:How to Modify HTTP Header of a request using C#?如何使用 C# 修改请求的 HTTP 标头?
【发布时间】:2011-04-27 21:02:12
【问题描述】:

我试图使用 C# 修改 HTTP 标头。我试图操纵 Page preinit 事件上的 Request.Headers。但是当我尝试为标头设置任何内容时,我得到 PlatformNotSupportedException。由于我们无法为 Reqeust.Headers 设置新的 NameValueCollection,因此我尝试使用以下代码设置该值:

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

知道如何实现吗?

【问题讨论】:

  • 您真的需要设置 Request(=incoming) 值,还是 Response 值 (=outgoing)?

标签: c# http-headers namevaluecollection


【解决方案1】:

试试这个:

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

编辑: 这可能是你的原因: http://bigjimindc.blogspot.com/2007/07/ms-kb928365-aspnet-requestheadersadd.html

其中有一个代码 sn-p,它为 Request.Headers 添加了一个新的标头。在 Windows 7 32 位操作系统上也经过验证。

但您可能想要替换该行:

HttpApplication objApp = (HttpApplication)r_objSender;

与:

HttpApplication objApp = (HttpApplication)HttpContext.Current.ApplicationInstance;

编辑: 要替换现有的 Header 值,请使用:

t.InvokeMember("BaseSet", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, new object[] { "Host", item });

其中“主机”是标头名称。

【讨论】:

  • 我得到 PlatformNotSupportedException。我使用带有 IIS 7.5 的 Windows 7 32 位
  • 我在 Win Server 2008、IIS 7、.Net Framework 3.5 SP1 上使用了上面的代码;效果很好
  • 对于使用 System.Net.HttpContent.Headers 的人,我使用 .Remove() 后跟 .Add(),以产生这种行为。 msdn.microsoft.com/en-us/library/…
【解决方案2】:

从链接的博客添加完整(工作)代码 - 以防该博客消失

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

【讨论】:

    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多