Write HttpModules and HttpHandlers

There are two options of extending the page-processing behavior of ASP.NET. These are HttpHandlers and HttpModules. I’ve already written a post about the former, which you can find here. HttpHandlers are parts of the ASP.NET infrastructure which are  responsible for processing a given request. Each request is served by exactly one handler. You can create your custom handlers by implementing the IHttpHandler or IHttpAsyncHandler interface.

Modules on the other hand provide a way to work with every given request. There are multiple modules working in ASP.NET for each request, for example, they are responsible for authentication, sessions, caching, and much more. Even better, they don’t override the default execution of the page life-cycle, so your forms will show up as usual. With the help of the IHttpModule interface, you can register events of the page life-cycle such as BeginRequest, or PostLogRequest. You can then add your own code into these events.

But what is the appropriate use of them?

Typical scenarios when using HttpHandlers is recommended:

  • Implementing RSS feeds: map a handler to the .rss extension and output formatted RSS feeds.
  • Image server: resize and do additional work with your images.

And the ones for HttpModule:

  • Security: you can monitor every incoming request, so modules are an ideal solution for security-related tasks such as authentication.
  • Statistics and logging: modules are called on every request, and this makes them an ideal candidate for counting users, etc.
  • Custom headers and footers: you can add custom header information to all pages, since you are working with all of them simultaneously.

Now you may have noticed the similarity of HttpModules and the global.asax file. Generally, you can implement much of the functionality of a module in the global.asax. However, modules has the following benefits over global.asax:

  • They are encapsulated, and can be reused.
  • They let you keep clear the global.asax.
  • They applies to all requests (when used in IIS 7 integrated mode).

But working with global.asax also has benefits. You can respond to events that aren’t available for modules. Such an event is Session_Start.

Further Readings

HTTP Handlers and HTTP Modules Overview

Implement the Generic Handler

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s