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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet

payment via phone

7 Ways Technology Has Changed Traditional Payments

In today’s digital world, technology has changed how we make payments. From contactless cards to mobile wallets, it’s now easier to pay for goods and services without carrying cash or using a checkbook. This article will look at seven of the most significant ways technology has transformed traditional payment methods.

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

Sitemap