HttpModule in Real Scenario: Implement Simple HttpModule

The purpose of this article is to understand the use of HttpHandler and HttpModule in real time software development.

This article series is explaining HttpHandler and HttpModule. The purpose of this article is to understand the use of HttpHandler and HttpModule in real time software development. In our previous few articles, we learned various concepts of HttpHandler. You can read them here.

·        From this article we will start to talk about HttpModule that is another interesting concept of the HTTP request and response pipeline process. As was explained earlier in this series something is not implemented for theoretical understanding, in this article we will understand the basic implementation of HttpModule and in future articles we will see a few realtime implementations with HttpModule. So, let’s start with some theory.

What HttpModule is

In the web and MSDN you will find a much better definition of HttpModule then my definition. Just for the sake an introduction I will just write a few lines about HttpModule. An HTTP module is an assembly that is called on every request to an application. It’s a part of the HTTP request and response pipeline.

Even the ASP.NET engine uses HttpModule to perform certain operations (which are outside our interests here). We are interested in implementing our own HttpModule that we will inject into a HTTP request and response pipeline.

Since the HttpModule executes in each and every request, we can implement such logic/checking that needs to be performed for each and every HTTP request or response. For example.

  • To check request type
  • To perform security checking
  • To log incoming requests from a different location for business needs

And many more that we will be implementing in future articles.

Ok, we have learned the basic concept of HttpModule. If not please consider any good reference of HttpModule for understanding the primary concept. We will now implement HttpModule in an ASP.NET application.

Implement simple HttpModule in ASP.NET application

This is the first example in the HttpModule series. Here we will learn to add a HttpModule to our ASP.NET application. So, create one empty Web application and add one .ashx file.

Once you add the file, just copy and paste the following code into that .ashx file.

As we said earlier, HttpModule is nothing but a chunk of code that we will inject into the HTTP request and response pipeline.

Here the chunk of code is nothing but a class. To implement the custom HttpModule we need to inherit our class from the IHttpModule interface That contains the Dispose() and Init() methods.

In the following example we have Implemented IHttpModule in the MyHttpModule class. The Init() method will execute first for any HTTP request.

So, this is our small MyHttpModule class implementation that is doing nothing in fact. We have just learned how to inject a HttpModule into a HTTP request and response pipeline process.

namespace WebApp
{
   
public class MyHttpModule : IHttpModule
    {
       
public void Dispose()
        {
            
throw new NotImplementedException();
        }

       
public void Init(HttpApplication context)
        {
           
throw new NotImplementedException();
        }
    }
}


We have created the HttpModule, now we will register it to inject it into the HTTP request pipeline. Just add the following code to the web.config file of your application.

 <modules>
        <add name="mymodule" type="WebApp.MyHttpModule"/>
 </modules>

The name part is provided for identification purposes and the type attribute is pointing to our custom HttpModule class with namespace.

Let’s run the application. We have halted the execution flow to see that the execution process hits the Init() method.



Fine, we have learned how to implement the simplest HttpModule in an ASP.NET application. Now, the general question may come to your mind, can we add more than one HttpModule in HTTP request and response pipeline?

Yes, we can. (We will see it in the next article of this series.)

In this example we will see a few events in HttpModule. (Though I am interested in writing one dedicated article on the same topic) . We have seen that the Init() method executes at first and then the various methods. In this example in the Init() method we will bind a few other events that will execute after execution of Init().

Now there is a sequence of event executions. In this example at first the BeginRequest() then Log Request () and then EndRequest() will execute.

Have a look at the following example. In this example we are interested in counting the number of incoming requests. To do that we need to log incoming requests within the LogRequest() event. Here is the implementation.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebApp
{
   
public class MyHttpModule : IHttpModule
    {
       
public void Dispose()
        {
           
throw new NotImplementedException();
        }

       
public void Init(HttpApplication context)
        {
            context.EndRequest +=
new EventHandler(end_request);
            context.BeginRequest +=
new EventHandler(begin_request);
            context.LogRequest +=
new EventHandler(log_request);
        }
       
public void log_request(object sender, EventArgs e)
        {
           
//Log operation goes here
           
HttpContext context = ((HttpApplication)sender).Context;
           
string url = context.Request.Path;
        }
       
public void begin_request(object sender, EventArgs e)
        {
          
        }
       
public void end_request(object sender, EventArgs e)
        {
          
        }

    }
}


We are seeing that the request has come for the “WebForm1.aspx” page. Now, if we want we can implement a count mechanism to count the number of incoming requests to that page (or any page).



Conclusion

In this article we have learned to implement a simple HttpHandler in an ASP.NET application. Though those examples are not a ful real time example, it is good to understand the basic concepts of HttpModule in an ASP.NET application.