HttpModule to add headers to request

前端 未结 2 609
粉色の甜心
粉色の甜心 2020-12-05 20:51

This seems like a simple operation.

We have a need in our development environment (running on XP/IIS 5) to add some headers into each HttpRequest arriving at our app

相关标签:
2条回答
  • 2020-12-05 21:00

    You can add to the Header this way. This is a way to add credential information to the request before it enter the authentication sequence.

    string cred = "UN:PW";
    System.Web.HttpContext.Current.Request.Headers.Add("Authorization", "Basic " +Convert.ToBase64String(Encoding.ASCII.GetBytes(cred)));
    
    0 讨论(0)
  • 2020-12-05 21:10

    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.

    0 讨论(0)
提交回复
热议问题