Dav*_*nna 10 c# iis httprequest http-headers
这似乎是一个简单的操作.
我们的开发环境(在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(){}
}
Run Code Online (Sandbox Code Playgroud)
但是在尝试这样做时,我发现Request的Headers集合是只读的,Add方法失败并带有OperationNotSupported异常.
花了几个小时在Google上研究这个问题,我对于应该是一个相对直接的问题没有简单的回答.
有没有人有任何指针?
Dav*_*nna 17
好的,在一位同事的协助和一些实验的帮助下,我发现这可以通过一些受保护的属性和通过反射访问的方法来完成:
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);
Run Code Online (Sandbox Code Playgroud)
这至少对我有用.
| 归档时间: |
|
| 查看次数: |
13592 次 |
| 最近记录: |