Monday, March 5, 2012

Changing session state at run time in ASP.NET 4.0

There are two places where you can enable or disable session state in Asp.NET

  • 1. Web.config
  • 2. @Page directive
ASP.NET 4.0 provides facility to enable and/or disable the session state at run time. I will not be going in details of configuring the session state by using above two technics you can learn this at link configuringsession states.

In this article I will exploring the new way ASP.NET 4.0 introduces of changing the session state programmatically at run time. Asp.NET 4.0 introduces new method SetSessionStateBehavior to the class HttpContext.


public void SetSessionStateBehavior(
                                                                           SessionStateBehavior sessionStateBehavior
                                                                          )

It accepts one parameter sessionStateBehavior which is of type enum SessionStateBehavior. This can have following values

Default: The default ASP.NET logic is used to determine the session state behavior for the request.
Required: Full read-write session state behavior is enabled for the request.
ReadOnly: Read-only session state is enabled for the request.
            Disabled:  Session state is not enabled for processing the request


Let us see how we can call this method to change the session state at run time. Make a note of the point that you should call this method before AcquireRequestState event gets called. If you call SetSessionStateBehavior method after this event then it will throw InvalidOperationException

So to use SetSessionStateBehavior facility create new HTTP module i.e. add new class and implement the IHttpModule interface; and hook BeginRequest event as shown below


Public class MySessionModule: IHttpModule
{
public void Init(HttpApplication context)
{  context.BeginRequest += new EventHandler(BeginRequest);
}

private void BeginRequest (object sender, EventArgs e)
{
HttpContext c = (sender as HttpApplication).Context;  c.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}

Practical use of SetSessionStateBehavior
So now we know how to change the session state of ASP.NET 4.0 at run time; now let us see why we may need this feature. Consider a scenario where you have website and some users of your website are say privileged users and when they log in to the site you want to enable the session state and when normal users say guest logs in you want to disable the session state.











No comments: