In Focus

Few Important Uses of HttpModule: Part 2

In this example we will measure the time taken by one HTTP request to complete.

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.

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using System.Linq;

using System.Security.Principal;

using System.Text;

using System.Web;

using System.Xml.Linq;

using Newtonsoft.Json;

namespace WebApp

{

    public class MyHttpModule1 : IHttpModule

    {

        public void Dispose()

        {

            throw new NotImplementedException();

        }

        public void Init(HttpApplication context)

        {

            context.BeginRequest += new EventHandler(OnBeginRequest);

            context.EndRequest += new EventHandler(OnEndRequest);

        }

 

        // Record the time of the begin request event.

        public void OnBeginRequest(Object sender, EventArgs e)

        {

            HttpApplication httpApp = (HttpApplication)sender;

            httpApp.Context.Items["beginTime"] = DateTime.Now;

        }

 

        public void OnEndRequest(Object sender, EventArgs e)

        {

            HttpApplication httpApp = (HttpApplication)sender;

 

            // Get the time of the begin request event.

            DateTime beginTime = (DateTime)httpApp.Context.Items["beginTime"];

 

            // Evaluate the time between the begin and the end request events.

            TimeSpan ts = DateTime.Now - beginTime;

 

            // Write the time span out as a request header.

            httpApp.Context.Response.AppendHeader("TimeSpan", ts.ToString());

 

            // Get the current user's Machine Name.

            string user = WindowsIdentity.GetCurrent().Name;

 

            // Display the information in the page.

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<H2>RequestTimeInterval from HttpModule Output</H2>");

            sb.AppendFormat("Current user: {0}<br/>", user);

            sb.AppendFormat("Time span between begin-request and end-request events: {0}<br/>",

                ts.ToString()); 

            httpApp.Context.Response.Output.WriteLine(sb.ToString());

        } 

    }  

}

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.

<system.webServer>

      <modules>

        <add name="mymodule1" type="WebApp.MyHttpModule1"/>

      </modules>

<system.webServer>

Here is the output of the receding 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.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="WebApp.login" %>

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        UserName:- <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />

        Password:- <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />

        <asp:Button ID="Login" runat="server" Text="Button" OnClick="Login_Click" />

    </div>

    </form>

</body>

</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.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Security;

using System.Web.Security;

namespace WebApp

{

    public partial class login : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

        } 

        protected void Login_Click(object sender, EventArgs e)

        {

            if(this.TextBox1.Text == "abc" && this.TextBox2.Text =="abc"){

            FormsAuthentication.SetAuthCookie(

                this.TextBox1.Text.Trim(),true); 

            Response.Redirect("Home.aspx");

            }

           

        }

    }

}

Step 3: Configure Form Authentication in web.config file

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

<authentication mode="Forms">

      <forms loginUrl="login.aspx">

      </forms>

    </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.

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using System.Linq;

using System.Security.Principal;

using System.Text;

using System.Web;

using System.Xml.Linq;

using Newtonsoft.Json;

namespace WebApp

{

    public class MyHttpModule1 : IHttpModule

    {

        public void Dispose()

        {

            throw new NotImplementedException();

        }

        public void Init(HttpApplication context)

        {

            context.AuthenticateRequest += new EventHandler(OnAuthentication);

        }

 

        void OnAuthentication(object sender, EventArgs a)

        {

            HttpApplication application = (HttpApplication)sender;

            HttpContext context = application.Context;

            if (context.Request.Url.AbsolutePath.Contains("Home"))

            {

                String user = context.User.Identity.Name;

            }

        }

    }  

}


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.