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.Dispos

       End Sub     



       Public Sub_context_PreSendRequestContent(ByVal sender As Object,_

                  ByVal e as EventArgs) Handles oApps.PreSendRequestContent

            Dim message as String = ""


            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 = "<!-- 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

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 !

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.