Click here to Skip to main content
15,499,155 members
Articles / Web Development / ASP.NET
Posted 25 Feb 2012

Tagged as


127 bookmarked

Implementing HTTPHandler and HTTPModule in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.75/5 (66 votes)
27 Feb 2012CPOL6 min read
This article aims at understanding the role of HTTPHandler and HTTPModule in ASP.NET applications.


This article aims at understanding the role of HTTPHandler and HTTPModule in ASP.NET applications. We will try to work on a basic example to see how these can be implemented.


ASP.NET handles all the HTTP requests coming from the user and generates the appropriate response for it. ASP.NET framework knows how to process different kind of requests based on extension, for example, It can handle request for .aspx, .ascx and .txt files, etc. When it receives any request, it checks the extension to see if it can handle that request and performs some predefined steps to serve that request.

Now as a developer, we might want to have some of our own functionality plugged in. We might want to handle some new kind of requests or perhaps we want to handle an existing request ourselves to have more control on the generated response, for example, we may want to decide how the request for .jpg or .gif files will be handled. Here, we will need an HTTPHandler to have our functionality in place.

There are also some scenarios where we are ok with the way ASP.NET is handling the requests but we want to perform some additional tasks on each request, i.e., we want to have our tasks execute along with the predefined steps ASP.NET is taking on each request. If we want to do this, we can have HTTPModule in place to achieve that.

So from the above discussion, it is clear that HTTPHandlers are used by ASP.NET to handle the specific requests based on extensions. HTTPModule, on the other hand, is used if we want to have our own functionality working along with the default ASP.NET functionality. There is one Handler for a specific request but there could be N number of modules for that.

Image 1

Using the Code

Let us try to understand these two concepts by writing a small application for each. What we will do is we will try to have a mechanism where we can process the web pages with extension like .bspx and .cspx. Although this is a very unrealistic scenario, a similar concept is used to have search engine friendly URLs so perhaps it's not that realistic either.

Note: The HTTPHandler example here is just for demonstration purpose, I am not recommending the use of HTTPHandlers for something that I am about to do now. HTTPHandlers should ideally be used to customize the handling of existing MIME types and not for serving search engine friendly URLs or non standard URLs.

Implementing the HTTPHandler

So with our problem definition, let us try to see how we can handle the request for .cspx pages using HTTPHandlers. First we need to have the handler class with us, so let us create the handler class.

public class CspxHandler :IHttpHandler
    public bool IsReusable
        get { return false; }

    public void ProcessRequest(HttpContext context)


The class should have a method ProcessRequest and a property called IsReusable. The property tells whether this handler can be reused or not and the method will be called whenever a request for that type comes. But wait, Where have we defined the type of request where this handler should be invoked? This can be defined either in IIS, if we have a handler common to all the sites running on that server or we can configure it in web.config file, if the handler is specific for a website. Let's do that in web.config file for now.

    <add verb="*" path="*.cspx" type="CspxHandler"/>

Here we registered our handler to specify that if any request for .cspx file comes, it should be forwarded to our handler.

Now, since we don't have any "real" files with .cspx extension, what we will do is we will handle the request for .cspx and in turn push the user to the corresponding .aspx file.

public class CspxHandler :IHttpHandler
    public bool IsReusable
        get { return false; }

    public void ProcessRequest(HttpContext context)
        context.Response.ContentType = "text/plain";

        if (context.Request.RawUrl.Contains(".cspx"))
            string newUrl = context.Request.RawUrl.Replace(".cspx", ".aspx");

Whenever a request for .cspx file comes, we will handle it in our handler and show the corresponding .aspx file instead. Let's see how it works.

Note: I have also changed the startup page name to Default.cspx but there is no page like that. I want my handler to handle that and show me the actual default page.

Image 2

Important: I reiterate, This example is just for illustration. This is not how HTTPHandlers should be used at all. HTTPHandlers should ideally be used to customize the handling of existing MIME types.

Well the pages seems to be working fine and the user will see .cspx URL for his request. But there is one problem. The way we wrote our handler is not good to handle the postback. If I add a button on any of these pages and do a postback, the original URLs will be visible. So it is not a good solution to the problem but it sure demonstrated the way Handlers can be used.

Implementing the HTTPModule

How do we solve the problem we just saw. Well, our application needed URL rewriting and HTTPHandlers are a bad solution for that and should never be used for that. So perhaps the guys using this technique to have search friendly URLs should rethink their strategy. SO how can we solve this problem really.

Let us look at the requirement again, All we needed was to show the user URLs which are different than the real URLs and process the real URLs internally. So we don't need custom handlers, we are ok with the way ASP.NET engine is handling these requests but we need custom activities to be done during the processing phase. So it looks like we can solve it using HTTPModule.

So let's go ahead and write an HttpModule that will:

  1. Check for file extension on request.
  2. If it finds a .bspx extension it changes it to .aspx (or find real URLS if we are implementing search friendly URLs)
  3. It will pass the request to the default handler, since the page is still aspx.
  4. Once the response is generated, it will write back the original .bspx URL to users browser.
public class MyBModule : IHttpModule
    public void Dispose()


    public void Init(HttpApplication context)
        context.BeginRequest += new EventHandler(context_BeginRequest);
        context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        context.EndRequest += new EventHandler(context_EndRequest);
        context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);

    void context_AuthorizeRequest(object sender, EventArgs e)
        //We change uri for invoking correct handler
        HttpContext context = ((HttpApplication)sender).Context;

        if (context.Request.RawUrl.Contains(".bspx"))
            string url = context.Request.RawUrl.Replace(".bspx", ".aspx");

    void context_PreRequestHandlerExecute(object sender, EventArgs e)
        //We set back the original url on browser
        HttpContext context = ((HttpApplication)sender).Context;

        if (context.Items["originalUrl"] != null)

    void context_EndRequest(object sender, EventArgs e)
        //We processed the request

    void context_BeginRequest(object sender, EventArgs e)
        //We received a request, so we save the original URL here
        HttpContext context = ((HttpApplication)sender).Context;

        if (context.Request.RawUrl.Contains(".bspx"))
            context.Items["originalUrl"] = context.Request.RawUrl;

Also we need to register our module so that it can be invoked, we will do that in our web.config file.

    <add name="MyBModule" type="MyBModule" />

And now let's run the application:

Image 3

So here we solved the problem of URL reverting back to the original on postback. This is also the ideal way of doing that.

Points of Interest

In this article, we saw how we can implement a basic HTTPHandler and HTTPModule. We saw each of their roles in page processing frameworks. We worked on an example that tried to solve the URL rewriting first the wrong way by using HTTPHandler (but we understood how to write HTTPhandler) and then the right way of doing URL rewriting using HTTPModule (we got to understand that too.

The emphasis of this article was solely on understanding how we can have HTTPHandlers and HTTPModules working. The example is a little unrealistic and perhaps a little misleading too but since I made that point really clear, it shouldn't be a problem.

Before wrapping up, there is one last thing that we should know about handlers. It is also possible to handle the request asynchronously. ASP.NET provides a mechanism for creating asynchronous handler and then increases the performance of a web page (implements the IHttpAsyncHandler do that).


  • 25 Feb 2012: Implementing HTTPHandlers and HTTPModules in ASP.NET


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

Written By
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more:[^]

  • Microsoft MVP 2015

Comments and Discussions

QuestionCan MVC Web Application launch from HttpPost Pin
Member 968331812-Sep-15 19:45
MemberMember 968331812-Sep-15 19:45 
Questionupdated for IIS7 and above Pin
New Admin10-Sep-15 20:47
MemberNew Admin10-Sep-15 20:47 
GeneralThank for this explanationw Pin
Girish Nama17-Nov-14 5:53
MemberGirish Nama17-Nov-14 5:53 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun3-Sep-14 5:00
MemberHumayun Kabir Mamun3-Sep-14 5:00 
Questiongeting error Pin
abdolwahab8-Aug-14 0:28
Memberabdolwahab8-Aug-14 0:28 
GeneralMy vote of 3 Pin
Member 1062364621-Jul-14 20:34
MemberMember 1062364621-Jul-14 20:34 
QuestionHTTP Module Event Hierachy Pin
nileshwar shukla13-May-14 3:00
professionalnileshwar shukla13-May-14 3:00 
QuestionProblem with filehandler Pin
Member 83044137-May-14 2:47
MemberMember 83044137-May-14 2:47 
QuestionGetting error Pin
Faiz Mohammad Ansari3-May-14 0:19
MemberFaiz Mohammad Ansari3-May-14 0:19 
QuestionNice article, simplest one i have found Pin
Sougata Mudi21-Apr-14 19:45
MemberSougata Mudi21-Apr-14 19:45 
QuestionNice & Clear Concept Pin
Ravi Sadalagi8-Apr-14 20:15
MemberRavi Sadalagi8-Apr-14 20:15 
QuestionVery Useful Pin
Member 10305803-Mar-14 0:05
MemberMember 10305803-Mar-14 0:05 
QuestionError Pin
Ami_Modi23-Jan-14 0:46
MemberAmi_Modi23-Jan-14 0:46 
AnswerRe: Error Pin
Jaison Devasia7-Apr-14 13:46
MemberJaison Devasia7-Apr-14 13:46 
GeneralRe: Error Pin
Jaison Devasia7-Apr-14 15:32
MemberJaison Devasia7-Apr-14 15:32 
QuestionGreatttt!!! Pin
paradisee13-Jan-14 8:15
Memberparadisee13-Jan-14 8:15 
QuestionWhy we are using context_PreRequestHandlerExecute event? Pin
Chetan Naithani6-Nov-13 10:56
professionalChetan Naithani6-Nov-13 10:56 
GeneralMy vote of 4 Pin
Mayuri Kulkarni8-Oct-13 21:02
MemberMayuri Kulkarni8-Oct-13 21:02 
GeneralMy vote of 5 Pin
S.P.Tiwari25-Jul-13 1:53
professionalS.P.Tiwari25-Jul-13 1:53 
GeneralMy vote of 4 Pin
Rukeshjee25-Jun-13 4:34
MemberRukeshjee25-Jun-13 4:34 
QuestionQuestion Pin
Nainil21-Apr-13 16:54
MemberNainil21-Apr-13 16:54 
GeneralMy vote of 5 Pin
Member 998151412-Apr-13 18:24
MemberMember 998151412-Apr-13 18:24 
GeneralMy vote of 5 Pin
vicvis28-Feb-13 13:01
Membervicvis28-Feb-13 13:01 
QuestionWhy HttpHandler is not best way Pin
HarshilG23-Jan-13 21:54
MemberHarshilG23-Jan-13 21:54 
QuestionNot Working Pin
chenthil2820-Jan-13 0:47
Memberchenthil2820-Jan-13 0:47 

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

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