Florence Blogspot about asp.net tutorials and web design and web development

Wednesday, February 6, 2008

Using HttpHandlers and HttpModules in your ASP.NET Websites

Using HttpHandlers and HttpModules in your ASP.NET Websites

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

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.




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




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 HandlersIn 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 codeThe above example, shows very basic things you can do with HttpHandler.

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 !

5 comments:

Anonymous said...

Hi,
These contants are fantastic; the information you show us is interesting for everybody and is really good written.

Flor said...

Thank you Rem and Sneha Gupta

Anonymous said...

thanks for this nice article

Anupama said...

Excellent content - as you always provide and inspires me to come again and again. You are on my RSS reader now.

jack said...

Hello Friends,
Nice post I am going to look around your site seems you have some great stuff.
Thanks:)

Search