The asp.net httprequest object provides information about the current http request made by the client browsers. So in this article, we will learn how we can add custom header into httprequest object for each aspx request even if this object is read only.
Introduction
The asp.net HttpRequest object provides information about the current http request made by the client browsers. So in this article, we will learn how we can add custom header into HttpRequest object for each aspx request even if this object is read only. In asp.net, every request made by the client browser goes through the asp.net application life cycle. In this life cycle there are several modules invokes to process the request after the iis handover the request to asp.net engine/asp.net ApplicationManager object.
After the asp.net engine start processing the request, the asp.net hosting environment creates HttpContext object of that asp.net application. After that the Http module is invokes for each request. The http module calls before and after the HttpHandler executes. so we can take advantage of http module to intercept the HttpHandler's request object and add custom header for each asp.net HttpRequest
HTTPModule Impletation
Create httpmodule by implementing IHttpModule interfacepublic class CustomeModule : IHttpModule
{public void Dispose()
{//clean-up code here.
}public void Init(HttpApplication context)
{context.BeginRequest += new EventHandler(context_BeginRequest);
}void context_BeginRequest(object sender, EventArgs e)
{var headers = HttpContext.Current.Request.Headers;
Type t = headers.GetType();
PropertyInfo prop = t.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic |BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
prop.SetValue(headers, false, null);
t.InvokeMember("BaseAdd", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, headers, new object[] { "CustomHeaderKey", new ArrayList { "Your CustomHeader Value of request object" } });
prop.SetValue(headers, true, null);
}
}add below web.config setting under <system.web> configuration setting
<httpModules >
<add name="CustomeModule" type="WebApplication70515.CustomeModule"/>
</httpModules>
ON page load event of the page see if the custome header value is available
here is the code of aspx.cs pagepublic partial class CustomHeaderTest : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e)
{if (Request.Headers["CustomHeaderKey"] != null)
{Response.Write(Request.Headers["CustomHeaderKey"]);
}
}
}
ConclusionIn the above article, we saw that even if the HttpRequest object is read only, still we can add custom headers for each asp.net request through httpmodule interceptor.
No comments :
Post a Comment