Few Important Uses of HttpModule: Part 1

This is the HttpHandler and HttpModule in real scenarios article series. In this series we are learning various concepts and uses of HttpHandler and HttpModule. In our previous articles we covered various important concepts, you can read them here.

In this article we will understand a few more concepts and uses of HttpModule. Those concepts and the situation is mapped with a practical problem and solution. So, let’s start with our first example.

Handle exception in HttpModule

Exception handling is a very common task in any application. We can handle an exception using the HttpModule.HttpContext has Error event and it executes when some exception occurs in the application. In this example we will handle an exception with the Error event of the HttpContext class. This is the implementation.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Drawing.Imaging;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Web;  
  8. using System.Xml.Linq;  
  9. using Newtonsoft.Json;  
  10. namespace WebApp  
  11. {  
  12.     public class MyHttpModule1 : IHttpModule  
  13.     {  
  14.         public void Dispose()  
  15.         {  
  16.             throw new NotImplementedException();  
  17.         }  
  18.         public void Init(HttpApplication context)  
  19.         {  
  20.             context.Error += new EventHandler(on_error);  
  21.         }     
  22.         public void on_error(object sender, EventArgs e)  
  23.         {  
  24.             //Log Operation goes here.  
  25.             HttpContext ctx = HttpContext.Current;  
  26.             HttpResponse response = ctx.Response;  
  27.             HttpRequest request = ctx.Request;  
  28.             Exception exception = ctx.Server.GetLastError();  
  29.             string errorInfo = "<p/>URL: " + ctx.Request.Url.ToString();  
  30.             errorInfo += "<p/>Stacktrace:---<br/>" +  
  31.                exception.InnerException.StackTrace.ToString();  
  32.             errorInfo += "<p/>Error Message:<br/>" +  
  33.                exception.InnerException.Message;  
  34.             response.Write("<p/>ErrorInfo:<p/>");  
  35.             response.Write(errorInfo);  
  36.             ctx.Server.ClearError();  
  37.         }  
  38.     }  
  39. } 
Ok, we have implemented our HttpModule that will trap an exception in the application. Now, take one .aspx page and write the following code in Page_Load(). It does nothing other than throwing one exception programmatically .
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     throw new Exception("My Exception");  
  4. } 
Here is the code to register the Handler in the request and response pipeline.
  1. <system.webServer>  
  2.       <modules>  
  3.         <add name="mymodule1" type="WebApp.MyHttpModule1"/>  
  4.      </modules>  
  5. </system.webServer> 
Now, if we run the application we will see the following screen. We are displaying all the information (including stack trace) about the exception. We will definitely not disclose that information to the user, it’s for our internal logging operations.



URL re-writing/redirection operation

This is another beautiful scenario where we can use HttpModule. URL re-write/redirection is the process where we want to map the old URL and new URL. Form example let’s think that in the old application there was one directory called “Home” and in the new application the directory has changed to “NewHome”. Now, we need to redirect all requests to the “Home” directory to the “NewHome” directory. This is a sample implementation of the problem.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Drawing.Imaging;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Web;  
  8. using System.Xml.Linq;  
  9. using Newtonsoft.Json;  
  10. namespace WebApp  
  11. {  
  12.     public class MyHttpModule1 : IHttpModule  
  13.     {  
  14.         public void Dispose()  
  15.         {  
  16.             throw new NotImplementedException();  
  17.         }  
  18.         public void Init(HttpApplication context)  
  19.         {  
  20.             context.BeginRequest += new EventHandler(begin_request);  
  21.         }  
  22.         public void begin_request(object sender, EventArgs e)  
  23.         {  
  24.             HttpContext Context = ((HttpApplication)sender).Context;  
  25.             string url = Context.Request.Url.AbsolutePath;  
  26.             if (url.Contains("Home"))  
  27.             {  
  28.                 url = url.Replace("Home""NewHome");  
  29.             }  
  30.             Context.Server.Transfer(url);  
  31.         }  
  32.     }  
  33. } 
The trick is very simple, we are getting the current URL within HttpModule and then checking whether or not the URL contains the “Home” keyword. If the keyword is present then we are just replacing with the new keyword and then we are just channeling the request to the next step.

In the following example we see that the URL has changed to “NewHome/WebFomr1.aspx”



This is one cool use of HttpModule.

Prevent any request type in the application

This is also one situation where HttpModule may come as a solution. There might be a situation where we want to prevent a request type in the application. In this example we will not allow a GET request in the application. If the request is a GET type then we will drop the request in the request pipeline and we will generate a default error message.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Drawing.Imaging;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Web;  
  8. using System.Xml.Linq;  
  9. using Newtonsoft.Json;  
  10. namespace WebApp  
  11. {  
  12.     public class MyHttpModule1 : IHttpModule  
  13.     {  
  14.         public void Dispose()  
  15.         {  
  16.             throw new NotImplementedException();  
  17.         }  
  18.         public void Init(HttpApplication context)  
  19.         {  
  20.             context.BeginRequest += new EventHandler(begin_request);  
  21.         }  
  22.         public void begin_request(object sender, EventArgs e)  
  23.         {  
  24.             HttpContext Context = ((HttpApplication)sender).Context;  
  25.             if (Context.Request.RequestType == "GET")  
  26.             {  
  27.                 Context.Response.Write("Get Request is not allowed in this application");  
  28.             }        
  29.         }  
  30.     }  
  31. } 
Here is the output of example above.


Conclusion

In this article, we learned a few pragmatic situations for implementing HttpModule as a solution. I hope those examples will help us to understand HttpModule better.

Next Article : Few Important Uses of HttpModule: Part 2


Similar Articles