Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

HTTP Module Pipeline and Session Creation in ASP.NET

0.00/5 (No votes)
6 Mar 2017 1  
This article explains the Session creation during HTTP Module pipeline

Introduction

Many of us are not able to understand the best place to create or access the session object earliest in the page execution. Here, I am trying to elaborate the details so this can be understood in the best way.

We have the below events in HTTP Module pipeline:

(Pre - Page Life Cycle)

  1. BeginRequest
  2. AuthenticateRequest
  3. AuthorizeRequest
  4. ResolveRequestCache
  5. AcquireRequestState
  6. PreRequestHandlerExecute

Post - Page life cycle

  1. PostRequestHandlerExecute
  2. ReleaseRequestState
  3. UpdateRequestCache
  4. EndRequest

The session is created during AcquireRequestState event.

Now, as we are aware, the first event in page life cycle is PreInit. If anyone tries to access the session at the top of the class itself, before PreInit method, it is not possible. Please see the example below:

public class MyPage : System.Web.UI.Page {
  private MyClass _myObj = new MyClass();
  ...

Here, we are trying to create the object of MyClass at the top of MyPage class before PreInit method. This MyClass has constructor as below:

public MyClass() 
{
  var mySession= HttpContext.Current.Session; // no problem here
  mySession["MyValue"] = 123;                 // throws null ref exception coz mySessionis null
}

This code will throw an exception because session handling is done at the wrong place.

The reason being:

In the request life cycle, this process of creation of object and execution of constructor is done during ResolveRequestCache, i.e., before AcquireRequestState event (since this is directly created in class and not any method). As expected, the session will still not be available in the constructor as AcquireRequestState is not yet executed.

PreInit method in page life cycle is called after AcquireRequestState and hence the session is available there.

Below is the sequence of execution of Page Life Cycle events:

  1. PreInit
  2. Init
  3. InitComplete
  4. PreLoad
  5. Load
  6. Load Complete
  7. PreRender
  8. PreRenderComplete
  9. SaveStateComplete

Conclusion

Earliest session operations can be done anytime after AcquireRequestState in Http Modules (if you are intercepting the request programmatically) or in/after PreInit method.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here