Click here to Skip to main content
11,634,634 members (69,604 online)
Click here to Skip to main content

The Two Interceptors: HttpModule and HttpHandlers

, 4 Mar 2009 CPOL 467K 3K 254
Rate this:
Please Sign up or sign in to vote.
The two interceptors: HttpModule and HttpHandlers

Table of Contents

Introduction

Many times we want to implement pre-processing logic before a request hits the IIS resources. For instance you would like to apply security mechanism, URL rewriting, filter something in the request, etc. ASP.NET has provided two types of interception HttpModule and HttpHandler. This article walks through it.

For the last few days, I have been writing and recording videos in design patterns, UML, FPA, Enterprise blocks and lot more. You can watch the videos here.

You can download my 400 .NET FAQ EBook from here.

The Problem

Many times we need to inject some kind of logic before the page is requested. Some of the commonly used pre-processing logics are stat counters, URL rewriting, authentication / authorization and many more. We can do this in the code behind but then that can lead to lot of complication and tangled code. The code behind will not solve the purpose because in some implementations like authorization, we want the logic to execute before it reaches the resource. ASP.NET provides two ways of injecting logic in the request pipeline HttpHandlers and HttpModules.

HttpHandler - The Extension Based Preprocessor

HttpHandler help us to inject pre-processing logic based on the extension of the file name requested. So when a page is requested, HttpHandler executes on the base of extension file names and on the base of verbs. For instance, you can visualize from the figure below how we have different handlers mapped to file extension. We can also map one handler to multiple file extensions. For instance, when any client requests for file with extension ‘GIF’ and ‘JPEG’, handler3 pre-processing logic executes.

HttpModule - The Event Based Preprocessor

HttpModule is an event based methodology to inject pre-processing logic before any resource is requested. When any client sends a request for a resource, the request pipeline emits a lot of events as shown in the figure below:

Below is a detailed explanation of the events. We have just pasted this from here.

  • BeginRequest: Request has been started. If you need to do something at the beginning of a request (for example, display advertisement banners at the top of each page), synchronize this event.
  • AuthenticateRequest: If you want to plug in your own custom authentication scheme (for example, look up a user against a database to validate the password), build a module that synchronizes this event and authenticates the user in a way that you want to.
  • AuthorizeRequest: This event is used internally to implement authorization mechanisms (for example, to store your access control lists (ACLs) in a database rather than in the file system). Although you can override this event, there are not many good reasons to do so.
  • PreRequestHandlerExecute: This event occurs before the HTTP handler is executed.
  • PostRequestHandlerExecute: This event occurs after the HTTP handler is executed.
  • EndRequest: Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information to the page.

We can register these events with the HttpModules. So when the request pipe line executes depending on the event registered, the logic from the modules is processed.

The Overall Picture of Handler and Modules

Now that we have gone through the basics, let's understand what is the Microsoft definition for handler and modules to get the overall picture.

Reference: INFO: ASP.NET HTTP Modules and HTTP Handlers Overview

“Modules are called before and after the handler executes. Modules enable developers to intercept, participate in, or modify each individual request. Handlers are used to process individual endpoint requests. Handlers enable the ASP.NET Framework to process individual HTTP URLs or groups of URL extensions within an application. Unlike modules, only one handler is used to process a request”.

Steps to Implement HttpHandlers

Step 1

HttpHandlers are nothing but classes which have pre-processing logic implemented. So the first thing is to create a class project and reference System.Web namespace and implement the IHttpHandler interface as shown in the below code snippet. IHttpHandler interface has two methods which needs to be implemented; one is the ProcessRequest and the other is the IsResuable. In the ProcessRequest method, we are just entering the URL into the file and displaying the same into the browser. We have manipulated the context response object to send the display to the browser.

using System;
using System.Web;
using System.IO;
namespace MyPipeLine
{
public class clsMyHandler : IHttpHandler
{
public void ProcessRequest(System.Web.HttpContext context)
{
context.Response.Write("The page request is " + context.Request.RawUrl.ToString());
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("Page requested at " + DateTime.Now.ToString() + 
			context.Request.RawUrl); sw.Close();
}
public bool IsReusable
{
get
{
return true;
}
}
}

Step 2

In step 2, we need to make an entry of HttpHandlers tag. In the tag, we need to specify which kind of extension requested will invoke our class.

<system.web>
<httpHandlers>
<add verb="*" path="*.Shiv,*.Koirala" type="MyPipeLine.clsMyHandler, MyPipeLine"/>
</httpHandlers>
</system.web>

Once done, request for page name with extension ‘Shiv’ and you should see a display as shown below. So what has happened is when the IIS sees that request is for a ‘.shiv’ page extension, it just calls the clsMyHandler class pre-processing logic.

Steps to Implement HttpModule

Step 1

As discussed previously, HttpModule is an event pre-processor. So the first thing is to implement the IHttpModule and register the necessary events which this module should subscribe. For instance, we have registered in this sample for BeginRequest and EndRequest events. In those events, we have just written an entry on to the log file.

public class clsMyModule : IHttpModule
{
public clsMyModule()
{}
public void Init(HttpApplication objApplication)
{
// Register event handler of the pipe line
objApplication.BeginRequest += new EventHandler(this.context_BeginRequest);
objApplication.EndRequest += new EventHandler(this.context_EndRequest);
}
public void Dispose()
{
}
public void context_EndRequest(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("End Request called at " + DateTime.Now.ToString()); sw.Close();
}
public void context_BeginRequest(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("Begin request called at " + DateTime.Now.ToString()); sw.Close();
}
}

Step 2

We need to enter those module entries into the HttpModule tag as shown in the below code snippet:

<httpModules>
<add name="clsMyModule" type="MyPipeLine.clsMyModule, MyPipeLine"/>
</httpModules>

The Final Output

If you run the code, you should see something like this in the RequestLog.txt. The above example is not so practical. But it will help us understand the fundamentals.

Begin request called at 11/12/2008 6:32:00 PM
End Request called at 11/12/2008 6:32:00 PM
Begin request called at 11/12/2008 6:32:03 PM
End Request called at 11/12/2008 6:32:03 PM
Begin request called at 11/12/2008 6:32:06 PM
End Request called at 11/12/2008 6:32:06 PM
Begin request called at 11/12/2008 8:36:04 PM
End Request called at 11/12/2008 8:36:04 PM
Begin request called at 11/12/2008 8:37:06 PM
End Request called at 11/12/2008 8:37:06 PM
Begin request called at 11/12/2008 8:37:09 PM
End Request called at 11/12/2008 8:37:09 PM
Begin request called at 11/12/2008 8:37:38 PM
Page requested at 11/12/2008 8:37:38 PM/WebSiteHandlerDemo/Articles.shiv
End Request called at 11/12/2008 8:37:38 PM

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Shivprasad koirala
Architect http://www.questpond.com
India India

I am an ex-Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos, writing books and corporate trainings. Do visit my site for 
.NET, C#, Design Pattern, WCF, Silverlight, LINQ, ASP.NET, ADO.NET, SharePoint, UML, SQL Server  training 
and Interview questions and answers


You may also be interested in...

Comments and Discussions

 
QuestionGood article Pin
ajayendra270714-Apr-15 21:45
memberajayendra270714-Apr-15 21:45 
GeneralSimple yet clear Pin
RaviKumarMvs15-Feb-15 23:35
memberRaviKumarMvs15-Feb-15 23:35 
QuestionHttphandler for Webdav Pin
Member 1130176224-Dec-14 9:48
memberMember 1130176224-Dec-14 9:48 
GeneralMy vote of 3 Pin
H.J25-Feb-14 1:04
memberH.J25-Feb-14 1:04 
QuestionAwesome article Pin
Suresh Dammannapeta30-Jan-14 22:50
memberSuresh Dammannapeta30-Jan-14 22:50 
GeneralMy vote of 5 Pin
Azziet11-Mar-13 2:52
memberAzziet11-Mar-13 2:52 
QuestionHttpHandlers are not Interceptors Pin
rajesh_chan28-Jan-13 17:38
memberrajesh_chan28-Jan-13 17:38 
GeneralMy vote of 5 Pin
shinnapongk9-Dec-12 14:52
membershinnapongk9-Dec-12 14:52 
QuestionWhich one is best? Pin
Vitaly Tomilov5-Oct-12 1:40
memberVitaly Tomilov5-Oct-12 1:40 
QuestionGetting Error Pin
Bitla Phanindra28-Sep-12 2:40
memberBitla Phanindra28-Sep-12 2:40 
AnswerRe: Getting Error Pin
Amol Borkar, Pune, India12-Oct-12 0:37
memberAmol Borkar, Pune, India12-Oct-12 0:37 
GeneralRe: Getting Error Pin
Bitla Phanindra12-Oct-12 2:23
memberBitla Phanindra12-Oct-12 2:23 
GeneralRe: Getting Error Pin
Amol Borkar, Pune, India15-Oct-12 4:46
memberAmol Borkar, Pune, India15-Oct-12 4:46 
GeneralRe: Getting Error Pin
Amol Borkar, Pune, India15-Oct-12 4:48
memberAmol Borkar, Pune, India15-Oct-12 4:48 
GeneralRe: Getting Error Pin
Bitla Phanindra15-Oct-12 21:29
memberBitla Phanindra15-Oct-12 21:29 
ok.. thanks
GeneralMy vote of 5 Pin
saanj11-Sep-12 23:15
membersaanj11-Sep-12 23:15 
GeneralMy vote of 5 Pin
sumanvidiyala6-Sep-12 16:03
membersumanvidiyala6-Sep-12 16:03 
GeneralMy vote of 5 Pin
Gerard Castelló Viader23-Aug-12 23:03
memberGerard Castelló Viader23-Aug-12 23:03 
Questionexcellent Pin
thinkindia4-Aug-12 5:43
memberthinkindia4-Aug-12 5:43 
GeneralHat's off to you sir..! Pin
shubhambhave3-Aug-12 3:28
membershubhambhave3-Aug-12 3:28 
QuestionVery Nice Explanation Pin
Member 823840818-Jun-12 20:57
memberMember 823840818-Jun-12 20:57 
QuestionNot able to implement HttpHandler for PDF file. Pin
kumardeff21-May-12 22:06
memberkumardeff21-May-12 22:06 
GeneralMy vote of 1 Pin
anurag.sri4313-Mar-12 23:57
memberanurag.sri4313-Mar-12 23:57 
Questioni want to create firewall at application level Pin
puspendra napit9-Feb-12 20:41
memberpuspendra napit9-Feb-12 20:41 
GeneralMy vote of 5 Pin
cool-sunil30-Nov-11 20:36
membercool-sunil30-Nov-11 20:36 
QuestionReally good explanation Pin
palakshamb16-Nov-11 1:13
memberpalakshamb16-Nov-11 1:13 
GeneralMy vote of 5 Pin
maq_rohit2-Oct-11 0:00
membermaq_rohit2-Oct-11 0:00 
GeneralMy vote of 5 Pin
SChristmas28-Jun-11 2:36
memberSChristmas28-Jun-11 2:36 
QuestionErrors with HttpModule practise Pin
kate08245-May-11 21:35
memberkate08245-May-11 21:35 
GeneralMy vote of 5 Pin
Sandeep Ramani13-Apr-11 3:16
memberSandeep Ramani13-Apr-11 3:16 
GeneralMy vote of 5 Pin
hhlovecode10-Apr-11 7:11
memberhhlovecode10-Apr-11 7:11 
GeneralMy vote of 5 Pin
jim lahey18-Feb-11 1:45
memberjim lahey18-Feb-11 1:45 
GeneralMy vote of 5 Pin
Soumya123410-Nov-10 1:12
memberSoumya123410-Nov-10 1:12 
GeneralAwesome on this one! Pin
Eric Xue (brokensnow)5-Nov-10 22:28
memberEric Xue (brokensnow)5-Nov-10 22:28 
GeneralExcellent Pin
ViralVasaiwala6-Oct-10 20:01
memberViralVasaiwala6-Oct-10 20:01 
GeneralMy vote of 5 Pin
nanjundappa19-Sep-10 18:57
membernanjundappa19-Sep-10 18:57 
GeneralHi Pin
Shabir Ahamed5-Sep-10 20:44
memberShabir Ahamed5-Sep-10 20:44 
Questiongetting this working with windows authentication if the login fails ??? Pin
jwaldner16-Aug-10 12:00
memberjwaldner16-Aug-10 12:00 
GeneralI am your FAN Pin
junkpraveen24-Oct-09 8:31
memberjunkpraveen24-Oct-09 8:31 
GeneralHttpModule with a Response.Filter and images not being displayed Pin
Member 166015113-Sep-09 2:03
memberMember 166015113-Sep-09 2:03 
GeneralThank you. Pin
yossefavr6-Sep-09 11:58
memberyossefavr6-Sep-09 11:58 
GeneralYou are the best.. Pin
rilov16-Aug-09 2:51
memberrilov16-Aug-09 2:51 
GeneralRe: You are the best.. Pin
Shivprasad koirala16-Aug-09 3:01
memberShivprasad koirala16-Aug-09 3:01 
GeneralGood Pin
Norm .net4-Mar-09 7:53
memberNorm .net4-Mar-09 7:53 
Generalvery good Pin
Donsw9-Feb-09 14:14
memberDonsw9-Feb-09 14:14 
Generalnice1 Pin
klace0622-Dec-08 8:54
memberklace0622-Dec-08 8:54 
GeneralNice one..Question Pin
kaishAgra26-Nov-08 21:19
memberkaishAgra26-Nov-08 21:19 
GeneralThanks :) Pin
Daniella24-Nov-08 8:20
memberDaniella24-Nov-08 8:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150728.1 | Last Updated 4 Mar 2009
Article Copyright 2008 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid