微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – HttpModule添加头来请求

这似乎是一个简单的操作.

我们在我们的开发环境(运行在XP / IIS 5)上需要在每个到达我们应用程序的HttpRequest中添加一些头文件. (这是为了模拟我们在dev中没有可用的生产环境).起初腮红,这似乎是一个简单的HttpModule,沿着以下行:

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异常.

在Google上花费了几个小时的时间研究这个问题,我已经没有想到应该是一个相对直截了当的问题的简单答案.

有人有任何指针吗?

解决方法

好的,在同事和一些实验的帮助下,我发现这可以通过反思访问的一些受保护的属性方法来进行:
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",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);

这对我来说至少是有用的.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐