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.

  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.             context.AuthenticateRequest += new EventHandler(authentication_request);  
  22.         }   
  23.         public void begin_request(Object sender, EventArgs e)  
  24.         {  
  25.         }  
  26.         public void authentication_request(Object sender, EventArgs e)  
  27.         {  
  28.             HttpContext Context = ((HttpApplication)sender).Context;  
  29.             if (Context.User == null)  
  30.             {  
  31.                 //User is not authenticated user. So drop request here.  
  32.                 Context.Response.Write("<h2><font color=red>" +  
  33.                                     "Please login before go ahead" +  
  34.                                     "</font></h2><hr>");  
  35.             }  
  36.         }   
  37.     }  
  38. } 

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.
  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 MyHttpModule1()  
  15.         {  
  16.             HttpContext.Current.Cache["DateTime"] = DateTime.Now.ToLongTimeString();  
  17.         }  
  18.         public void Dispose()  
  19.         {  
  20.             throw new NotImplementedException();  
  21.         }  
  22.         public void Init(HttpApplication context)  
  23.         {  
  24.             context.BeginRequest += new EventHandler(begin_request);  
  25.             context.PostResolveRequestCache += new EventHandler(resolve_request_cache);  
  26.         }   
  27.         public void begin_request(Object sender, EventArgs e)  
  28.         {  
  29.         }  
  30.         public void resolve_request_cache(Object sender, EventArgs e)  
  31.         {  
  32.             HttpContext Context = ((HttpApplication)sender).Context;  
  33.             Context.Response.Write("Time is:-" + HttpContext.Current.Cache["DateTime"]);  
  34.         }  
  35.     }  
  36.   }  
  37. } 

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.

  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.AcquireRequestState += new EventHandler(AcquireRequestState);  
  21.         }  
  22.         public void AcquireRequestState(Object sender, EventArgs e)  
  23.         {  
  24.             HttpContext Context = ((HttpApplication)sender).Context;  
  25.             Context.Session.Add("Item""Session Data");  
  26.         }  
  27.     }  
  28. } 

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. 

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     Response.Write(Session["Item"].ToString());  
  4. }

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.


Similar Articles