Few Important Uses of HttpModule: Part 2

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

This is another example where we can measure the time gap between a request and its response. Sinice HttpModule is in the middle of a request and response, we can measure the time taken by a specific HTTP request.

In this example we will measure the time taken by one HTTP request to complete. Have a look at the following example.

  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.Security.Principal;  
  8. using System.Text;  
  9. using System.Web;  
  10. using System.Xml.Linq;  
  11. using Newtonsoft.Json;  
  12. namespace WebApp  
  13. {  
  14.     public class MyHttpModule1 : IHttpModule  
  15.     {  
  16.         public void Dispose()  
  17.         {  
  18.             throw new NotImplementedException();  
  19.         }  
  20.         public void Init(HttpApplication context)  
  21.         {  
  22.             context.BeginRequest += new EventHandler(OnBeginRequest);  
  23.             context.EndRequest += new EventHandler(OnEndRequest);  
  24.         }  
  25.         // Record the time of the begin request event.  
  26.         public void OnBeginRequest(Object sender, EventArgs e)  
  27.         {  
  28.             HttpApplication httpApp = (HttpApplication)sender;  
  29.             httpApp.Context.Items["beginTime"] = DateTime.Now;  
  30.         }  
  31.         public void OnEndRequest(Object sender, EventArgs e)  
  32.         {  
  33.             HttpApplication httpApp = (HttpApplication)sender;  
  34.             // Get the time of the begin request event.  
  35.             DateTime beginTime = (DateTime)httpApp.Context.Items["beginTime"];  
  36.             // Evaluate the time between the begin and the end request events.  
  37.             TimeSpan ts = DateTime.Now - beginTime;  
  38.             // Write the time span out as a request header.  
  39.             httpApp.Context.Response.AppendHeader("TimeSpan", ts.ToString());  
  40.             // Get the current user's Machine Name.  
  41.             string user = WindowsIdentity.GetCurrent().Name;  
  42.             // Display the information in the page.  
  43.             StringBuilder sb = new StringBuilder();  
  44.             sb.AppendLine("<H2>RequestTimeInterval from HttpModule Output</H2>");  
  45.             sb.AppendFormat("Current user: {0}<br/>", user);  
  46.             sb.AppendFormat("Time span between begin-request and end-request events: {0}<br/>",  
  47.                 ts.ToString());   
  48.             httpApp.Context.Response.Output.WriteLine(sb.ToString());  
  49.         }   
  50.     }  
  51. } 

The implementation is pretty simple. When a request is coming we are recording the time and when the request finishs we again measure the time and then calculate the time taken by that specific HTTP request to complete.

Add the following code to your web.config file to register the HttpModule.

  1. <system.webServer>  
  2.       <modules>  
  3.         <add name="mymodule1" type="WebApp.MyHttpModule1"/>  
  4.       </modules>  
  5. </system.webServer> 

Here is the output of the preceding implementation. We see that the HTTP request is taking nearly 2 miliseconds to finish. (Ha..Ha..Pretty fast execution).

http request
 
Count number of requests by user by Form authentication

This is another real situation where we can implement HttpModule as a solution. Sometimes it’s very useful to count the number of login attemts from a specific user. There might be a business need or other motive behind that (we are not concerned with it).

So, if the requirement is something like. “We need to count the number of logins of a specific user, then we can implement the counting mechanism using HttpModule. I am not demanding that, this is the best and only one solution in this reqirement, but this is also a possible solution among others.

When we want to count the login attempts of a user then we need to count with respect to username and for that we will implement Form Authentication in the application.

Step 1: Create login form with a few controls

Here is the code of the login form. It’s very simple. We just must use two text boxes with one button.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="WebApp.login" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>  
  10.         UserName:- <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />  
  11.         Password:- <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />  
  12.         <asp:Button ID="Login" runat="server" Text="Button" OnClick="Login_Click" />  
  13.     </div>  
  14.     </form>  
  15. </body>  
  16. </html> 

Step 2: Write the following code in code behind of login form

This is the normal form of Authentication code, nothing special in this. We are checking the username and password with a constant string, in reality it might check with some persistence storage. Once both the username and password is “abc” we are setting the form authentication cookies and then redirecting the user to the Home page.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Security;  
  8. using System.Web.Security;  
  9. namespace WebApp  
  10. {  
  11.     public partial class login : System.Web.UI.Page  
  12.     {  
  13.         protected void Page_Load(object sender, EventArgs e)  
  14.         {  
  15.         }   
  16.         protected void Login_Click(object sender, EventArgs e)  
  17.         {  
  18.             if(this.TextBox1.Text == "abc" && this.TextBox2.Text =="abc")   
  19.             {  
  20.                 FormsAuthentication.SetAuthCookie(  
  21.                     this.TextBox1.Text.Trim(),true);   
  22.                 Response.Redirect("Home.aspx");  
  23.             }  
  24.         }  
  25.     }  
  26. } 

Step 3: Configure Form Authentication in web.config file

This is necessary when we want to configure Form Authentication in an ASP.NET application.

  1. <authentication mode="Forms">  
  2.       <forms loginUrl="login.aspx">  
  3.       </forms>  
  4. </authentication> 

Step 4: Implement HttpModule that will count user

Here is the core part of this example. We will implement one HttpModule that will count the user depending one URL.

Have a look at the following code. Here we will detect the user who will try to browse to the Home.aspx page.

  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.Security.Principal;  
  8. using System.Text;  
  9. using System.Web;  
  10. using System.Xml.Linq;  
  11. using Newtonsoft.Json;  
  12. namespace WebApp  
  13. {  
  14.     public class MyHttpModule1 : IHttpModule  
  15.     {  
  16.         public void Dispose()  
  17.         {  
  18.             throw new NotImplementedException();  
  19.         }  
  20.         public void Init(HttpApplication context)  
  21.         {  
  22.             context.AuthenticateRequest += new EventHandler(OnAuthentication);  
  23.         }  
  24.         void OnAuthentication(object sender, EventArgs a)  
  25.         {  
  26.             HttpApplication application = (HttpApplication)sender;  
  27.             HttpContext context = application.Context;  
  28.             if (context.Request.Url.AbsolutePath.Contains("Home"))  
  29.             {  
  30.                 String user = context.User.Identity.Name;  
  31.             }  
  32.         }  
  33.     }  
  34. } 

We are checking the URL, If the URL pattern contains the keyword Home then will check the username as it’s showing in the following example.

url pattern

And when we are getting the username it’s very simple to implement a counting mechanism depending on username. I have skipped this part to make the example simple. With a little effort, you can implement the rest.

Conclusion

In this article, we have learned two important concepts for implementing HttpModule as a solution. I hope you have understood the real example of HttpModule in this article.


Similar Articles