Basically HTTP Module is a .NET class that executes for every page request. Use an HTTP Module to handle any of the HttpApplication events that handle in the Global.asax file.
There are several HTTP Module which are available already in ASP.Net Framework. For example, FormsAuthenticationModule used to implement Forms authentication and the WindowsAuthenticationModule used to implement Windows authentication in Asp.Net. Asp.Net Framework uses the SessionStateModule to handle session state, OutputCacheModule to handle output caching and ProfileModule to handle Profile object.
When you request any page, HTTPApplication class loads all HTTP modules mentioned in Web.Config file.
Creating HTTP Module in Asp.Net is very easy. Just implement the IHttpModule interface which has Init(, Dispose() methods and register this custom module in web.config file.
For example you have one admin page which is allowed by only admin users and identify the admin user based on query string parameter “role”. If the value of role is admin, user has admin permissions else normal user. For that create custom HTTP Module in Asp.Net as shown below.
public class AspNetHTTPModule:IHttpModule
{
public AspNetHTTPModule()
{
}
#region IHttpModule Members
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication context)
{
context.AuthorizeRequest += new EventHandler(AuthorizeRequestForAdmin);
}
private void AuthorizeRequestForAdmin(Object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpContext context = app.Context;
// If the request is for Default.aspx, exit
string path = context.Request.AppRelativeCurrentExecutionFilePath;
if (String.Compare(path.ToLower(), "~/default.aspx", true) == 0)
return;
bool authorized = false;
if (context.Request.QueryString["role"] != null)
{
if (context.Request.QueryString["role"].ToLower() == "admin")
authorized = true;
}
// If not authorized, redirect to Default.aspx
if (!authorized)
context.Response.Redirect("Default.aspx");
}
#endregion
}
Register this HTTP Module in web.config under httpModules section as shown below.
<httpModules>
......
<addname="AspNetHTTPModule"type="AspNetHTTPModule"/>
</httpModules>
For testing provide the two links on Default.aspx page one with query string parameter role value as admin and another with query string parameter role value as normal. Click on first link, redirected to AdminPage.aspx page and click on second link, redirected to same Default.aspx because query string parameter role value is not equal to admin.