Implement Custom HttpHandler And Custom HttpModule

This blog explains the role of HTTPHandler and HTTPModule in ASP.NET applications. We will try to work on a basic example to see how these can be implemented and how we can create our own custom HttpHandler and custom HttpModule.

When a client makes a request for a resource located on the server in an ASP.NET application, each request is handled by the HTTP Handlers. Microsoft ASP.NET has a number of built-in HTTP Handlers which serve different files like .ascx, .ASPX, .ASMX etc. Based on the extension of the file, the appropriate HTTP Handlers get loaded which is mapped to the extension and is responsible for processing the ASP.NET request.

HttpHandlers are responsible for handling HTTP requests. So whenever a user requests a file, it is processed by the handler based on the extension. So, custom HTTP handlers are created when you need to special handling based on the file name extension.

HTTPHandlers are classes that implement IhttpHandler and generate a response to HttpRequest.

How to create custom HttpHandler -

  1. Create a class which implements IHttpHandler interface.

  2. Expose properties and Method IsReusable and ProcessRequest
  1. using System;  
  2. using System.Web;  
  3.   
  4. namespace HttpHandlerAndHttpModule  
  5. {  
  6.     public class AppShutDownHandler : IHttpHandler  
  7.     {  
  8.         #region Custome HTTPHandler   
  9.   
  10.         public bool IsReusable  
  11.         {  
  12.             // Return false in case your Managed Handler cannot be reused for another request.  
  13.             // Usually this would be false in case you have some state information preserved per request.  
  14.             get { return true; }  
  15.         }  
  16.   
  17.         public void ProcessRequest(HttpContext context)  
  18.         {  
  19.             context.Response.Write("<h1 style='Color:blue; font-                                       size:15px;'>Our website is under maintainace. Please try after some time</h1>"); 
  20.         }  
  21.  
  22.         #endregion  
  23.     }  
  24. }
  25.   

 To register custom handler we need to write below lines in Web.config as below

  1. <httpHandlers>  
  2.   <add verb="*" path="*.aspx" type="HttpHandlerAndHttpModule.AppShutDownHandler"/>  
  3.   <add verb="*" path="*.html" type="HttpHandlerAndHttpModule.AppShutDownHandler"/>  
  4. </httpHandlers>  
Things to notice here -

IsReusable is a property which by default returns false but you can set to yes according to your need.

ProcessRequest is a method where you can write your logic for custom handler. As per the above snippet, we have created it based on file extension. If the user tries to access .aspx file or .html file, then this handler will execute and respond to that request. Let's try to access Home.aspx and Home.html file and check our custom handler.

 
Let's try to access Home.html from web url.
 
ASP.NET 
 
HttpModule  

HttpModules are classes that implements IHttpModule interface and are designed to respond to life cycle events.

Multiple HttpModule can respond to single httprequest,

HttpModules brings the reusability, modules written once can be reused in several applications across the framework.

Logging and authentication are the best examples of HttModule. So here, I have chosen a Logger example to demonstrate Custom HttpModule example

How to create custom HttpModule

  1. Create a class which implements IHttpModule interface.

  2. Expose two Methods Init() and Dispose()
  1. using System;  
  2. using System.IO;  
  3. using System.Web;  
  4.   
  5. namespace CustomHttpModule  
  6. {  
  7.     public class CustomLoggerHttpModule : IHttpModule  
  8.     {  
  9.         private StreamWriter sw;  
  10.         private string filePath = @"c:\users\jigneshkumar.b\documents\visual studio 2015\Projects\CustomHttpModule\CustomHttpModule\logger.txt";  
  11.         public void Dispose()  
  12.         {  
  13.             //clean-up code here.  
  14.         }  
  15.   
  16.         public void Init(HttpApplication context)  
  17.         {  
  18.             // custom logging implementation, hooking event in init Method 
  19.             context.BeginRequest += new EventHandler(this.Application_BeginRequest);  
  20.             context.EndRequest += new EventHandler(this.Application_EndRequest);  
  21.         }  
  22.   
  23.         private void Application_BeginRequest(Object source, EventArgs e)  
  24.         {  
  25.             if (!File.Exists(filePath))  
  26.             {  
  27.                 sw = new StreamWriter(filePath);  
  28.             }  
  29.             else {  
  30.                 sw = File.AppendText(filePath);  
  31.             }  
  32.             sw.WriteLine("User sent request at {0}", DateTime.UtcNow);  
  33.             sw.Close();  
  34.         }  
  35.   
  36.         public void Application_EndRequest(Object source, EventArgs e)  
  37.         {  
  38.             if (!File.Exists(filePath))  
  39.             {  
  40.                 sw = new StreamWriter(filePath);  
  41.             }  
  42.             else  
  43.             {  
  44.                 sw = File.AppendText(filePath);  
  45.             }  
  46.             sw.WriteLine("User request completed at {0}", DateTime.UtcNow);  
  47.             sw.Close();  
  48.         }  
  49.     }  
  50. }  

Now we have done with custom HttpModule so we need to register this Module in Web.config file. We need to add the below line for module section --  runAllManagedModulesForAllRequests -- the option needs to be set as true.

  1. <modules runAllManagedModulesForAllRequests="true" 
  2.    <remove name="FormsAuthentication" />  
  3.    <remove name="ApplicationInsightsWebTracking" />  
  4.    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />  
  5.    <add name="CustomHttpModule" type="CustomHttpModule.CustomLoggerHttpModule"/>  
  6.  </modules>  

In the above code snippet we have hooked two events, Application_BeginRequest and Application_EndRequest in Init(). So when a user request comes it will log the request's start time and once the request ends it will log the  request's completed time. Have a look at the below snippet for output logger.txt file

ASP.NET
 
Hope you enjoyed reading. Cheers.  

Thank you for reading.