Create HttpModules for ASP.NET Pluggable Functionality

Create HttpModules for ASP.NET Pluggable Functionality

by David Hayden ( Microsoft MVP C# )

 

HttpModules are old hat to experienced developers who have been developing in ASP.NET for years, but today I teamed up with some newer ASP.NET developers who were not aware of the power of HttpModules for providing pluggable functionality to ASP.NET applications. Better yet, HttpModules can be built with no changes to existing applications and can be activated and deactivated by simply adding and removing them from the Web.config file.

HttpModules get added to the HttpRequest Pipeline and are called before and after the HttpHandler executes. HttpModules enable developers to intercept, participate in, or modify each individual request.

 

HttpModules

 

You can register your own modules by means of the <httpModules> Configuration Section in the Web.config file.

 

<system.web>
    <httpModules>
        <add name="MyModule" type="Class, Assembly" />
    </httpModules>
</system.web>

 

Modules implement the IHttpModule interface, which is located in the System.Web namespace. As an example, a common HttpModule you may find is one that logs unhandled exceptions in your ASP.NET Application by hooking into the HttpApplication's Error Event:

 

public class ExceptionLoggingModule : IHttpModule
{
    #region IHttpModule Members

    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        context.Error += new EventHandler(context_Error);
    }

    void context_Error(object sender, EventArgs e)
    {
        // Log the Error...
    }

    #endregion
}

 

If you are new to ASP.NET development and have not experienced the joys of HttpModules, do yourself a favor and build a couple to experience the power and extensibility at your fingertips. They are seriously cool.

Here are a few older posts where I talked about HttpModules, but the Internet is filled with many others:

 

News Feed: David Hayden ( Microsoft MVP C# )

 

posted on Monday, September 24, 2007 5:48 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices