要的HttpModule头添加请求 [英] HttpModule to add headers to request
问题描述
这似乎是一个简单的操作。
This seems like a simple operation.
我们有必要在我们的开发环境(在XP / IIS 5上运行),以一些头添加到每个Htt的prequest在我们的应用程序到达。 (这是为了模拟生产环境,我们没有在dev的可用)。乍一看,这似乎是一个简单的HttpModule,沿着线:
We have a need in our development environment (running on XP/IIS 5) to add some headers into each HttpRequest arriving at our application. (This is to simulate a production environment that we don't have available in dev). At first blush, this seemed like a simple HttpModule, along the lines of:
public class Dev_Sim: IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += delegate { app.Context.Request.Headers.Add("UserName", "XYZZY"); };
}
public void Dispose(){}
}
但在试图做到这一点,我发现请求的标题集合是只读的,而Add方法失败,出现OperationNotSupported例外。
But on trying to do that, I find that the Headers collection of the Request is read-only, and the Add method fails with an OperationNotSupported exception.
花费一两个小时在谷歌研究这个,我来了没有简单的答案是什么应该是一个比较直接的问题。
Spending a couple hours researching this on Google, I've come up with no easy answer to what should be a relatively straight-forward problem.
有没有人有任何指针?
推荐答案
好吧,与同事和一些实验的协助下,我发现,这可能与一些保护属性和方法,通过反射访问的协助下完成
Okay, with the assistance of a co-worker and some experimentation, I found that this can be done with the assistance of some protected properties and methods accessed through 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);
这工作对我来说,至少。
This works for me, at least.
这篇关于要的HttpModule头添加请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!