HttpModule and HttpHandler

HttpModule and HttpHandler provide mechanism to execute some logic before the page is requested. In this blog I will create a simple demo which shows the utility of these two components.


HttpHandler is an extension based preprocessor.  That means that HttpHandler executes logic based on the file extension and the verbs. We can write different handlers for different types of files. Only one handler is used to process a request.
HttpModule is an event based preprocessor. That means that HttpModule executes logic based on the event registered. Multiple modules can be registered for a request.
Let's take a look at an example. In this example we will create a simple web app with the default aspx page. Then we will create 2 HttpModules and 1 HttpHandler. For each event provided by HttpModule, we will just add a string to the response. This way at the end we will know the sequence in which this execution takes place. 
First lets take a look at the HttpHandler. To create an HttpHandler, we need to implement the interface IHttpHandler. This handler has a ProcessRequest() method which gets the current HttpContext.
Now, lets take a look at the HttpModule. To create an HttpModule, we need to implement the IHttpModule interface.  This module has a Init() method which get the current Application object. 
To register these handlers and modules, we need to navigate to the config file as shown below. As you can see, for the handler, we set the type, name, verb and path properties. In our case, it means that for all the pages with extension aspx this module will get executed.
When I run the application, this is the output I see -