HttpModule为请求添加标头

时间:2010-11-03 20:03:06

标签: c# iis http-headers httprequest

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

我们的开发环境(在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方法失败并带有OperationNotSupported异常。

花了几个小时在谷歌上研究这个问题,我对这应该是一个相对直接的问题没有简单的回答。

有没有人有任何指示?

2 个答案:

答案 0 :(得分: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);

这至少对我有用。

答案 1 :(得分:0)

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

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