WorldofASP.NET : ASP.NET Tutorial, Hosting, and Source Code

WorldofASP.NET >> ASPNET >> HttpHandlers and HttpModules

Using HttpHandlers and HttpModules in your ASP.NET Websites

How to use HttpHandlers and HttpModules on your ASP.NET websites and why you need to use them

Published Date : 03 Sep 2007

Author : Handy Chang
Language : VB.NET,C#
Platform : .NET
 
Technology : Visual Studio,ASP.NET
Views : 2070
Rating : (0 votes so far)
Email to a Friend | Print this Article | Add to Favourites | Report Error

Introduction

In this article I would explain about HttpModules and HttpHandlers and how to use it on your Website.
Sometimes, just creating dynamic Web pages with the latest languages and databases just does not give you , the developer enough control over an application. At times, you need to be able to dig deeper and create applications that can interact with the Web Server itself. You want to be able to interact with the low level processes such as how the Web Server processes incoming and outgoing HTTP requests.

Before ASP.NET, in order to get this level of control using IIS, you were forced to create ISAPI extensions or filters. This proved to be quite daunting and painful task for many developers because creating ISAPI extensions and filters required knowledge of C/C++ and knowledge of how to create native Win32 DLLs. Thankfully, in .NET world, creating these types of low level applications is really no more difficult than most other tasks you would normally perform.

HttpModules

HttpModules are simple classes that can plug themselves into the request processing pipeline. They do this by hooking into a handful events thrown by the application as it processses the HTTP request. To create an HttpModule, you simply create a class that derives from the System.Web.IHttpModule interface. This interface requires you to implement two methods: Init and Dispose. The code snippet below will show you how to implement the methods.

Code in VB.NET

    Imports Microsoft.VisualBasic
    Imports System.Web

    Public Class SimpleHttpModule Implements IHttpModule
        Public Overridable Sub Init(ByVal context as HttpApplication) _
               Implements IHttpModule.Init
        End Sub

        Public Overridable Sub Dispose() Implements IHttpModule.Dispose
        End Sub
    End Class
Code in C#
    using System;
    using System.Web;
    
    public class SimpleHttpModule :IHttpModule {
        public void Dispose() {
        } 
        
        public void Init(HttpApplication context) {
        } 
    } 


The Init Method is the primary method that you use to implement the functionality. Notice that it has single method parameter named HttpApplication object named context. The parameter gives you access to the current HttpApplication context and it is what you use to wire up the different events that fired during the request processing.

Below is the list of the important EventName that you can use with the HttpApplication object.
1.  AcquireRequestState.
     Raised when ASP.NET runtime is ready to acquire the SessionState of the current Http request

2.  AuthenticateRequest.
     Raised when ASP.NET runtime is ready to authenticate the identity of the user.

3.  AuthorizeRequest
     Raised when ASP.NET runtime is ready to authorize the user for the resources user is trying to   
     access.

4.  BeginRequest
    
Raised when ASP.NET runtime receivess a new HTTP request.

5.  End Request
     Raised just before sending the response content to the client

Simple Example using HTTPModule

The example below will showsyou how to modified the HTTP output stream before it get sent to the client. This can be a simple and useful tool if you want to add text to each page served from  your Website but do not want to modify each page.

Code in VB.NET

    Public Class SimpleHTTPModule Implements IHttpModule
        Dim WithEvents oApps as HttpApplication = Nothing

        Public Overridable Sub Init(ByVal context as HttpApplication) _ 
            Implements IHttpModule.Init
            oApps = context
        End Sub
       
        Public Overridable Sub Dispose() Implements IHttpModule.Dispose
        End Sub
        
        Public Sub_context_PreSendRequestContent(ByVal sender As Object,_ 
                   ByVal e as EventArgs) Handles oApps.PreSendRequestContent
             Dim message as String = "<!-- This page is being processed at " &amp; _
             System.DateTime.Now.ToString() &amp; " -->"
  
             oApps.Context.Response.Output.Write(message);
        End Sub

    End Class
Code in C#
     public class SimpleHTTPModule : IHttpModule
     {
          private HttpApplication oApps = null;

          public void Dispose() {
          } 
  
          public void Init(System.Web.HttpApplication context) {
              oApps = context;
              context.PreSendRequestContent += new EventHandler
              (context_PreSendRequestContent);
          }
          
          void context_PreSendRequestContent(object sender,EventArgs e) {
               string message = "&lt;!-- This page is being processed at " +
               System.DateTime.Now.ToString() + " -->"
  
               oApps.Context.Response.Output.Write(message);
          }
     }

You can see from the code snippet above, we are using PreSendRequestContent event. This event fires right before the content is sent to the client and you have the last opportunity to modify it.

In the PreSendRequestContent handler method, you simply create a string containing an HTML comment that contains the current time. You take this string and write it to the current HTTP requests output stream. The Http request is then sent back to the client.

In order to use this module, you must let ASP.NET know that you want to include this module in the request pipeline. You can add the httpmodule section by modifying your web.config file.
     <system.web>
         <httpModules>
             <add name="SimpleHTTPModule" type="SimpleHTTPModule,App_code"/>
         </httpModules>
     </system.web> 

The generic format of the httpModules in your web.config file is

     <system.web>
         <httpModules>
             <add name="modulename" type="namespace.classname,assemblyname"/>
         </httpModules>
     </system.web> 

If you have created your HttpModule in  the App_code directory of an ASP.NET project, you might wonder how you know the assemblyname value should be,considering ASP.NET 2.0 now dynamically compiles your code at runtime. The solution is to use the text App_code as the assembly name. This tells ASP.NET that your module is located in the dynamically located assembly.

You can also create HttpModules as a separate class library project in which case you simply use the assembly name of the library.

After you have added this section on your web.config file, try to run any file of your web project and view source the generated aspx file. You should be able to see the commented date time as we previously coded in the http modules.

HttpHandlers

HttpHandlers differ from HttpModules not only because of their positions in  the request processing pipeline, but also because they must be mapped to a specific file extensions. HttpHandlers are the last stop for the incoming Http requests and are ultimately the point in the request processing pipeline that is responsible for serving up the requested content, be it in ASPX page,HTML,plain text or an image. Additionally HttpHandlers can offer significant performance gains.

In this arcticle, I will demonstrate two different ways to create a simple HttpHanlder that you can use to serve up dynamic images. First you look at creating an HttpHanlder using an ASHX file extension. Then you learn how you get even more control by mapping your HttpHandler to a custom file extension using IIS.

Generic Handlers
In Visual Studio 2005, Microsoft has introduced new template specifically for HttpHandler and it ends with .ashx extension. The .ashx extension is the default HttpHander file extension set up by ASP.NET.

Remember that HttpHandlers must be mapped to a unique file extensions. But luckily in asp.net 2.0, they have .ashx file extension that specifically created for HttpHandler purpose. This will save you heaps of time configuring and adding new file extension on your web.project

Outputting an image from HttpHandler

<@ WebHandler Language="VB" Class="Handler"/>
Imports System.Web

Public Class Handler:Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context as HttpContext) _
             Implements IHttpHandler.ProcessRequest
          context.Response.ContentType = "image/jpeg"
          context.Response.WriteFile("Sunset.jpg")
    End Sub
    
    Public ReadOnly Property IsReusable() As Boolean _ 
           Implements IHttpHandler.IsReusable
         Get 
             Return False
         End Get
    End Property
End Class
<@ WebHandler Language="C#" Class="Handler"/> 
using System.Web 
     public class Handler:IHttpHandler { 
          public void ProcessRequest(HttpContext context) {                
              context.Response.ContentType = "image/jpeg"; 
              context.Response.WriteFile("Sunset.jpg"); 
     } 
     public bool IsReusable { 
         get{ 
            return false; 
         }
     } 
} 

As you can see, simply change the ContentType method to image/jpeg to indicate that you are returning JPEG image, then you use the WriteFile() method to write an image file to the output stream.

To use the handler, you can directly called the .ashx file from your html code
<img src="ImageHandler.ashx"/>

The above example, shows very basic things you can do with HttpHandler. I have another more advanced example in using HttpHandler to manipulate images dynamically.
Please check the url below

http://www.worldofasp.net/aspnet/Tutorials/images/Displaying_images_in_ASP.NET_using_HttpHandlers_92.aspx

Conclusion

The article above is basically an introduction to the HttpHandler and HttpModules. Lots of ASP.NET developers until now never use and never heard about HttpHandlers and HttpModules. The reason is because they keep applying  the old way and old technology from Classic ASP 3.0. You can do the similar thing without the need of using HttpHandler and HttpModules. However using HttpHandler and HttpModules allow your website to be more manageable, extensible and less code written in your presentation layer. You encapsulate all the logic inside the HttpHandler and HttpModules. Thats all for now. Happy  programming !



Other Related and Popular Articles :

Displaying images in ASP.NET using HttpHandlers
This article explains about HttpHandlers and how you can use them to display images in ASP.NET.
ASP.NET HTTP Modules:
HTTP Modules use to intercept HTTP requests for modifying or utilize HTTP based requests according to need.

Author Profile : Handy Chang

I work in a Software House Company in Malaysia (Kuala Lumpur) and I am MCP Certified in C# and Web Application course.
I originally started my programming in Java but later on changed to Microsoft platform because of the simplicity and ease of use.
I love .NET programming and am doing it almost every day now.

Click here to view Author Profile


How would you rate the quality of this content?
Poor Excellent

Comments

#httprequest
11 May 2008 16:55 by : arun solanki

if u can help me plz mail to me at ymca.arun@gmail.com
language c#

#httprequest
11 May 2008 16:54 by : arun solanki

how can i find out more such https like-
("http://www.amazon.com/exec/obidos/search-handle-form/102-5194535-6807312");

Leave New Comments


Article Content copyright by Handy Chang
Everything else Copyright © by WorldofASP.NET 2008
 
Announcements
Earn Cash Now







Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap | Link To Us | Contact Us
© 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | Windows Web Hosting | FREE ASP.NET CMS | Phone Card | PHP Directory | Bangkok Hotels |Calling Card