jump to navigation

Programmatically Changing Session State Behavior in ASP.NET 4.0 January 15, 2011

Posted by Abhijit Jana in ASP.NET 4.0, General, Visual Studio 2010.
Tags: , ,
trackback

Session is one of most important state management in ASP.NET. We can enable or disabled session state either in web.config or using @Page directive’s   EnableSessionState attributes. But there was no provision to change the session state at runtime till date in ASP.NET. But using  ASP.NET 4.0, we can change the session  state programmatically . The .NET 4.0 framework adds a new method SetSessionStateBehavior  to the HttpContext class for ASP.NET. This method required SessionStatebehavior  value to set the current session mode. To call SetSessionStateBehavior   simply create a new HttpModule by Implementing IHttModule and hook the BeginRequest event. Most important you can only use the SetSessionStateBehavior  until the AcquireRequestState event is fired, because AcquireRequestState  Occurs when ASP.NET acquires the current state  that is associated with the current request

While calling SetSessionStatebehavior, You can pass the following values as SessionStatebehaimagevior  :

  • Default: This is default setting which means  everything works as before
  • Disabled: Turned of Session Sate for Current Request.
  • ReadOnly: Read only access to Session State;
  • Required: Enabled session state for both Read and Write Access;


Let’s have a look into a quick example where I will show how you can change the session state based on the different member types of your web site. Let’s say you have 3 different types of member (Gold, Silver and Platinum) and You want for Platinum member you want to maintain the session for some specific pages not for other. To start with this first, create an new HTTP Module by implementing IHttpModule Interface.

using System;
using System.Web;

/// <summary>
/// Summary description for SessionModule
/// </summary>
public class SessionModule : IHttpModule
{
    /// <summary>
    /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
    /// </summary>
    public void Dispose() { }

    /// <summary>
    /// Initializes a module and prepares it to handle requests.
    /// </summary>
    /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    /// <summary>
    /// Handles the BeginRequest event of the context control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    void context_BeginRequest(object sender, EventArgs e)
    {
        HttpContext currentContext = (sender as HttpApplication).Context;    

        if (!string.IsNullOrEmpty(currentContext.Request.QueryString["memberType"]))
        {
            if (currentContext.Request.QueryString["memberType"].ToString().Equals("Platinum"))
            {
                currentContext.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
            }
        }

  
    }
}

From the above code block. you can see, based on the member type which is nothing but an query string, I am changing the session state.

image
Now, if you have Session disabled in @Page Directive, it will automatically override the settings.

image

Once you have done with implementation of HTTP Module,  you have to configure web.config for the same.

image 

Again, you have to make sure that,y ou can only use SetSessionStateBehavior   until the AcquireRequestState event is fired.

And, not only with Query string, you can enable or disable session state based on the different page as show in below

image

To know more about ASP.NET 4.0 State management, you can read my Session notes on Microsoft Community Tech Days – Hyderabad

Download ASP.NET 4.0 State Management – Deep Dive PPT

You will get the complete demo application on runtime session state change from above download.
Hope this will help you !

Cheers !

AJ

Comments»

1. Programmatically Changing Session State Behavior in ASP.NET 4.0 … - Internet Education Blog - worldstudychannel.com - November 30, 1999

[...] Original post: Programmatically Changing Session State Behavior in ASP.NET 4.0 … [...]

2. Dew Drop – January 15, 2011 | Alvin Ashcraft's Morning Dew - November 30, 1999

[...] Programmatically Changing Session State Behavior in ASP.NET 4.0 and How to pass external values with GridView HyperLinkField which are not part of your Gridview DataSource member ? (Abhijit Jana) [...]

3. Tweets that mention Programmatically Changing Session State Behavior in ASP.NET 4.0 « Abhijit's World of .NET -- Topsy.com - January 15, 2011

[...] This post was mentioned on Twitter by Shravan Kumar. Shravan Kumar said: RT @AbhijitJana: Programmatically Changing Session State Behavior in ASP.NET 4.0: http://wp.me/ppvPE-zU [...]

4. Programmatically Changing Session State Behavior in ASP.NET 4.0 - January 15, 2011

[...] attributes. But there was no provision to change the session state at runtime till… [full post] Abhijit Jana Abhijit's World of .NET generalvisual studio 2010asp.net 4.0 0 [...]

5. Few important tips that you should know while using ASP.NET Session - Daily .Net Tips - May 3, 2011

[...] is one of my complete article, where I have discussed about details of SetSessionStatebehavior which talks about the details implementation, use with real [...]

6. Few important tips that you should know while using ASP.NET Session - Abhijit's Blog - May 3, 2011

[...] is one of my complete article, where I have discussed about details of SetSessionStatebehavior which talks about the details implementation, use with real [...]

7. Few important tips that you should know while using ASP.NET Session « Abhijit's World of .NET - May 3, 2011

[...] is one of my complete article, where I have discussed about details of SetSessionStatebehavior which talks about the details implementation, use with real [...]

8. Product Placement - December 16, 2011

That was very informational read!!!

9. Ankit Singh - January 12, 2012

Very nice article. I really enjoying it, and it also cleared lot of my doubts about Asp.Net session state. Thanks for sharing with us. Following link also helped me lot to understand the Asp.Net Session
State…

http://mindstick.com/Articles/273b0c21-a027-46ec-8c84-ad4e05c62b23/?Session%20state%20in%20ASP.Net

Thanks everyone for your precious post!!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,745 other followers

%d bloggers like this: