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)
BeginRequest
AuthenticateRequest
AuthorizeRequest
ResolveRequestCache
AcquireRequestState
PreRequestHandlerExecute
Post - Page life cycle
PostRequestHandlerExecute
ReleaseRequestState
UpdateRequestCache
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;
mySession["MyValue"] = 123;
}
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:
PreInit
Init
InitComplete
PreLoad
Load
Load Complete
PreRender
PreRenderComplete
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.