HttpModule为请求添加标头

这看似简单的操作。

我们的开发环境(在XP / IIS 5上运行)需要在每个到达我们应用程序的HttpRequest中添加一些头文件。 (这是为了模拟我们在开发中没有的生产环境)。 乍一看,这看起来像一个简单的HttpModule,沿着这样的方向:

public class Dev_Sim: IHttpModule { public void Init(HttpApplication app) { app.BeginRequest += delegate { app.Context.Request.Headers.Add("UserName", "XYZZY"); }; } public void Dispose(){} } 

但是在尝试这样做时,我发现Request的Headers集合是只读的,Add方法失败并带有OperationNotSupportedexception。

花几个小时在谷歌上研究这个问题,我找不到一个应该是一个相对直接的问题的简单答案。

有没有人有任何指针?

好的,在同事和一些实验的帮助下,我发现这可以通过一些受保护的属性和通过reflection访问的方法来完成:

 var headers = app.Context.Request.Headers; Type hdr = headers.GetType(); PropertyInfo ro = hdr.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); // Remove the ReadOnly property ro.SetValue(headers, false, null); // Invoke the protected InvalidateCachedArrays method hdr.InvokeMember("InvalidateCachedArrays", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, null); // Now invoke the protected "BaseAdd" method of the base class to add the // headers you need. The header content needs to be an ArrayList or the // the web application will choke on it. hdr.InvokeMember("BaseAdd", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, new object[] { "CustomHeaderKey", new ArrayList {"CustomHeaderContent"}} ); // repeat BaseAdd invocation for any other headers to be added // Then set the collection back to ReadOnly ro.SetValue(headers, true, null); 

这至少对我有用。

您可以通过这种方式添加到标题中。 这是一种在请求进入身份validation序列之前向请求添加凭据信息的方法。

 string cred = "UN:PW"; System.Web.HttpContext.Current.Request.Headers.Add("Authorization", "Basic " +Convert.ToBase64String(Encoding.ASCII.GetBytes(cred)));