HttpModule in Real Scenario: Events in HttpModules

This is the “HttpHanlder and HttpModule in real scenario” article series. The purpose of this article is to understand the real-time uses of HttpHandler and HttpModule in ASP.NET application development. In our previous article, we saw a few practical examples of HttpHandler and we started to talk about HttpModule. You can read them here.

In our previous HttpModule article we saw that we can bind various events associated with a HTTP request and response context.

In this article we will talk about various events and their execution sequence in an ASP.NET application. Here is the list of events depending on execution sequence.

BeginRequest

Request has been started. If you need to do something at the beginning of a request (for example, display advertisement banners at the top of each page or some variable initialization).

AuthenticateRequest

If you want to plug in your own custom authentication scheme (for example, look up a user against a database to validate the password or checking of header information in HTTP request).

AuthorizeRequest
 
This event is used internally to implement authorization mechanisms (for example, to store your Access Control Lists (ACLs) in a database rather than in the file system).

ResolveRequestCache

This event determines if a page can be served from the Output Cache. If you want to write your own caching module (for example, build a file-based cache rather than a memory cache) then synchronize this event to determine whether to serve the page from the cache or a fresh page will be generated.

AcquireRequestState

Session state is retrieved from the state store. If you want to build your own state management module then synchronize this event to grab the Session state from your state store.

PreRequestHandlerExecute

This event occurs before the HTTP handler is executed.

PostRequestHandlerExecute

This event occurs after the HTTP handler is executed.

ReleaseRequestState
 
Session state is stored back in the state store. If you are building a custom session state module then you must store your state back in your state store.

UpdateRequestCache

This event writes output back to the Output Cache.

EndRequest

Request has been completed.

It does rely impossible to understand those entire events by reading once. To understand them with a practical example we need to implement them one by one in an application. In this example we will try to understand a few of them.

Check whether or not it is authenticated

We can perform the authentication process within an AuthenticateRequest event. In this example we will check whether the user’s authentication is performed before processing the request.

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using System.Linq;

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(begin_request);

            context.AuthenticateRequest += new EventHandler(authentication_request);

        } 

        public void begin_request(Object sender, EventArgs e)

        { 

        }

        public void authentication_request(Object sender, EventArgs e)

        {

            HttpContext Context = ((HttpApplication)sender).Context;

 

            if (Context.User == null)

            {

                //User is not authenticated user. So drop request here.

                Context.Response.Write("<h2><font color=red>" +

                                    "Please login before go ahead" +

                                    "</font></h2><hr>");

            }

        } 

    }  

}

If the User property is blank then we are assuming that the user is not authenticated and it’s an anonymous request to the application. So that we are dropping the request by showing the ,following message.

authenticated

Implement Caching in HttpModule

This is another real-time use of HttpModule in an ASP.NET HTTP request and response pipeline. We all understand the concept of caching in a Web application. In this example we will implement the concept of caching in HttpModule.

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using System.Linq;

using System.Web;

using System.Xml.Linq;

using Newtonsoft.Json;

namespace WebApp

{

    public class MyHttpModule1 : IHttpModule

    {

        public MyHttpModule1()

        {

            HttpContext.Current.Cache["DateTime"] = DateTime.Now.ToLongTimeString();

        }

 

        public void Dispose()

        {

            throw new NotImplementedException();

        }

        public void Init(HttpApplication context)

        {

            context.BeginRequest += new EventHandler(begin_request);

            context.PostResolveRequestCache += new EventHandler(resolve_request_cache);

        } 

        public void begin_request(Object sender, EventArgs e)

        {

        }

        public void resolve_request_cache(Object sender, EventArgs e)

        {

            HttpContext Context = ((HttpApplication)sender).Context;

            Context.Response.Write("Time is:-" + HttpContext.Current.Cache["DateTime"]);

        } 

    }  

  }
}

The trick is very simple , we are setting the date time within Cache within the constructor of the HttpHandler and then we are accessing the cached object from the PostResolveRequestCache event. Once we run the application, we will get the following output in each and every run from the same instance.

Caching in HttpModule

Initiate session data in very first of HTTP request / response pipeline

This example might not solve any real-time problem, but we can understand a good concept that may help us any other day of application development or interview panel. If someone asks you , from which event the session starts in an ASP.NET application then the following example will provide the answer.

We can start accessing the session state from the AccureRequestState event of a HTTP request response pipeline.

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using System.Linq;

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.AcquireRequestState += new EventHandler(AcquireRequestState);

        }

        public void AcquireRequestState(Object sender, EventArgs e)

        {

            HttpContext Context = ((HttpApplication)sender).Context;

            Context.Session.Add("Item", "Session Data");

        } 

    }  

}

We see that we have set the session within the AcquireRequestState event and then we will access it form our Web Form.

Here is the code of the Web Form. We are just printing the session variable.

protected void Page_Load(object sender, EventArgs e)

{

    Response.Write(Session["Item"].ToString());

}

In the output, we are getting the string that we had set in the session in the HTTP pipeline.

HTTP request response pipeline

Conclusion

In this article we learned how to work with various events in a HttpModule in an ASP.NET application. I hope it will help you to understand HttpModule better. In the next article we will see a few more practical examples of HttpModule.