Extending ASP.NET with HttpHandlers and HttpModules

Extending ASP.NET with HttpHandlers and HttpModules

ASP.NET provides a robust framework for your Web applications. However, at times it becomes necessary to go beyond the out-of-the-box functionality.

For example, when you request a resource such as an HTML page or ASP page using the browser, IIS processes that resource based on its file extension. IIS processes ASP pages using a DLL named asp.dll. Similarly, IIS processes ASP.NET (.aspx) pages with the aspnet_isapi.dll. But sometimes you may need to process custom file extensions. Suppose you’re developing a Web application that makes frequent use of graphics generated on-the-fly that display charts. You might want those files to use a custom file extension?for example .chart.

ISAPI Extensions and Filters
Before ASP.NET, the only way to process custom file extensions was to write an ISAPI (Internet Service Application Programming Interface) extension or an ISAPI filter. However, writing ISAPI extensions and filters is difficult, requires strong C/C++ skills, and is considered “out of reach” for many programmers. ASP.NET improves the situation greatly. ASP.NET’s HttpExtensions and HttpModules provide functionality similar to ISAPI Extensions and ISAPI filters, respectively. Writing HttpHandlers and HttpModules is just a matter of implementing certain interfaces.

HttpExtensions let you process a particular extension (or a set of extensions) using custom code.

Similarly, HttpModules let you filter client requests. For example, you could use an HttpModule if you wanted to manipulate the requested URL by changing the file names before letting the ASP.NET engine handle the request?thus hiding the real file names from the clients. Unlike HttpExtensions, HttpModules execute for every request?irrespective of the file extension. You can create an HttpModule to tweak the request either before or after the appropriate handler processes it.

From a programmer’s point of view, HttpHandlers and HttpModules are nothing but classes that implement certain interfaces. HttpHandlers must implement the IHttpHandler interface. Some built-in classes such as HttpApplication and Page already implement the IHttpHandler interface. Similarly, new HttpModule-derived classes must implement the IHttpModule interface. Again, the Framework contains built-in classes such as FormsAuthenticationModule and WindowsAuthenticationModule that already implement the IHttpModule interface. Both interfaces reside in the System.Web namespace.

The IHttpHandler interface is extremely simple. The interface consists of a read only property named IsReusable, which returns a Boolean value (typically true) indicating whether another request can use the IHttpHandler instance, and a ProcessRequest method, which takes a parameter of type HttpContext and performs the job of handling the extension.

   [Visual Basic]   ReadOnly Property IsReusable As Boolean   Sub ProcessRequest(ByVal context As HttpContext)      [C#]   bool IsReusable {get;}   void ProcessRequest(HttpContext context);

I used VB.NET for the sample code, but you can use the .NET language of your choice. First, launch VS.NET, create an empty project (MyHttpHandler in the sample code), and add a new class to it. Add a reference to the System.Web namespace and add an Imports System.Web statement at the top of the class file. Add an Implements statement to add the IHttpHandler interface. The following code shows the class with an empty interface implementation.

   Imports System.Web      Public Class ChartHandler      Implements IHttpHandler         Public ReadOnly Property IsReusable() As Boolean          Implements System.Web.IHttpHandler.IsReusable         Get         End Get      End Property         Public Sub ProcessRequest( _         ByVal context As System.Web.HttpContext) _         Implements _         System.Web.IHttpHandler.ProcessRequest         End Sub   End Class

This example simply outputs some text in response to a request. Add the following code to implement the ProcessRequest method :

   Public Sub ProcessRequest( _      ByVal context As System.Web.HttpContext) _      Implements System.Web.IHttpHandler.ProcessRequest      Context.Response.Write _         ("

Output of Chart " & _ "Handler

") End Sub

Note how you gain access to the Response object via the HttpContext parameter.

Next, implement the IsReusable property as follows:

   Public ReadOnly Property IsReusable() _      As Boolean _      Implements IHttpHandler.IsReusable      Get         Return True      End Get   End Property 

The property simply returns True. Compile the project. Next, you must configure it.

Configuring the HttpHandler in IIS
After you develop an HttpHandler or HttpModule you must configure IIS and ASP.NET for the new code to take effect. There are actually two steps involved in running a custom HttpHandler. First, you use the IIS Application Configuration dialog to map the file extension to the ASP.NET engine. Second, you modify the configuration sections in the application’s web.config file to specify the namespace and class you want to use to handle that extension.

For IIS, you add the required file extension in the Application Configuration dialog as shown in Figure 1. You can add or remove handlers using this dialog.

HttpModules intercept each request to Web application resources. The class that is to act as HttpModule must implement an interface called IHttpModule. Again, the interface is simple:

   [Visual Basic]   Sub Init(ByVal context As HttpApplication)   Sub Dispose()            [C#]   void Init(HttpApplication context);   void Dispose(); 

To implement the IHttpModule interface, you need only write two methods: Init and Dispose. The Init method receives an HttpApplication parameter. You can alter the request either before or after the handler for that request executes by trapping the HttpApplication BeginRequest and EndRequest events. You write event handlers for these events in the Init method. The Dispose method lets you clean up any unmanaged resources.

To get started, just as with the HttpHandler example, create an empty project and add a class to it. Add a reference to the System.Web assembly and add the Imports statement in the new class. To implement IHttpHandler interface, use the AddHandler statement and write methods to handle the HttpApplication’s BeginRequest and EndRequest events, for example:

   Imports System.Web      Public Class TweakRequestModule      Implements IHttpModule         Public Sub Init(ByVal app As HttpApplication) _         Implements IHttpModule.Init         AddHandler app.BeginRequest, _            AddressOf MyBeginRequest         AddHandler app.EndRequest, _            AddressOf MyEndRequest      End Sub         Public Sub Dispose() Implements IHttpModule.Dispose         ' add clean-up code here if required      End Sub         Public Sub MyBeginRequest(ByVal s As Object, _         ByVal e As EventArgs)         Dim app As HttpApplication         app = CType(s, HttpApplication)         app.Response.Write _            ("

Request Begins Here...

") End Sub Public Sub MyEndRequest(ByVal s As Object, _ ByVal e As EventArgs) Dim app As HttpApplication app = CType(s, HttpApplication) app.Response.Write _ ("

Request Ends Here...

") End Sub End Class

The code attaches event handlers to the HttpApplication instance using the AddHandler statement. The event-handlers themselves (MyBeginRequest and MyEndRequest) perform the actual work to write HTML messages.

Configuring an HttpModule in Web.config
You must modify the configuration settings in web.config to let ASP.NET know about the HttpModule. This time, you don’t need to create a new Web project to test the code; instead, add a new Web form in the Web application you created for the HttpHandler sample project and then modify the web.config file. The following fragment shows the section.


As before, you need to specify the type and assembly details of the module. After saving the configuration changes, run the Web Form. You’ll see the output in Figure 4.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist

©2024 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.