Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Programmatically Changing Session State Behavior in ASP.NET 4.0

, 15 Jan 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Programmatically Changing Session State Behavior in ASP.NET 4.0

Session is one of the most important state managements in ASP.NET. We can enable or disable 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 importantly, 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 the default setting which means everything works as before
  • Disabled: Turned of Session State 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 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;

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

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

    /// <span class="code-SummaryComment"><summary>
</span>    /// Handles the BeginRequest event of the context control.
    /// <span class="code-SummaryComment"></summary>
</span>    /// <span class="code-SummaryComment"><param name="sender">The source of the event.</param>
</span>    /// <span class="code-SummaryComment"><param name="e">The <see cref="System.EventArgs"/> 
</span>    /// instance containing the event data.<span class="code-SummaryComment"></param>
</span>    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 are done with implementation of HTTP Module, you have to configure web.config for the same.

image

Again, you have to make sure that you 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 shown below:

image

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

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

Cheers !

AJ


Filed under: ASP.NET 4.0, General, Visual Studio 2010

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Abhijit Jana
Technical Lead
India India
.NET Consultant | Former Microsoft MVP - ASP.NET | CodeProject MVP, Mentor, Insiders| Technology Evangelist | Author | Speaker | Geek | Blogger | Husband
 
Blog : http://abhijitjana.net
Web Site : http://dailydotnettips.com
Twitter : @AbhijitJana
My Kinect Book : Kinect for Windows SDK Programming Guide
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 5 PinmvpKunal_Chowdhury23-Jan-11 8:57 
GeneralMy vote of 5 PinmvpAbhishek Sur15-Jan-11 22:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411023.1 | Last Updated 16 Jan 2011
Article Copyright 2011 by Abhijit Jana
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid