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?
ASP.NET uses HTTP Handlers to process any HTTP requests made for managed web pages. You can customize the default behavior by implementing custom handlers for custom file types. This is a process rather simple; you should do three things to accomplish it, then some debugging. All will be specified here:
- Write the code that handles the requests
- Configure IIS to pass the requests to ASP.NET
- Configure ASP.NET to process the requests by specifying file extensions
The classic example of creating a generic handler is to build an image handler. We will do the same, too. First add a new Generic Handler to your web site. This will create an .ashx file in the solution. By default, the code will be generated in the same file. This is not desired for us, because when you’ve ended, and try to run your app, it won’t work.