Article
One Community, One World
ASP.NET Server-Based State Management, Part02: Session State
by Ahmed Rafie  on Jun 23 2007 12:00AM
  PageViews 7334   |    Add to Fav   |     Send to Friend   |    no downloads available

Introduction
In this part of article, we will take a look of how to use session state to store and retrieve values. Unlike application state which stores variables that can be accessed by all users of an asp.net application. Session state identifies requests from the same browser during a limited time window as a session, and provides the ability to persist variable values for the duration of that session. 

Session variables 
Session variables are stored in a SessionStateItemCollection that is exposed through the session property of the HTTPContext class. By default, session variables can be any valid .net type, these variables indexed by the name of the variables or by an integer index. Session variables are created by simply referring to the session variable by name.

Session identifiers
Sessions are identified using a unique identifier stored in the SessionID. SessionID values are transmitted between the browser and the web server in a cookie or in URL if cookieless sessions are specified. This ID can enable ASP.NET application to associate a specific browser with related session data and information on the web server.

Cookieless SessionIDs:
If you do not want to use cookie to store SessionID which is done by default, you can set the Cookieless attribute to true in the SessionState section in web.config file.

Asp.net modifies the page's URL by inserting a unique ID just before sending each page to the browser.

Http://www.hut.com/s(kwi55zl255xlv22c44)/test.aspx

The following example shows a web.config file that configures on asp.net application to use cookieless session identifiers.

C#
<configuration>   
    <system.web>     
        <sessionState cookieless="true" regenerateExpiredSessionId="true" />   
    </system.web>
</configuration>



Regenerating expired session identifiers
By default the session ID values are recycled, if a request is made with a session ID that has expired, a new session is stored using the session ID supplied with the request. This behavior can result in sharing of session data with multiple browsers. To disable the recycling, set the regenerateexpeiredsessionid attribute of the sessionstate configuration element to true. This will result in a new sessionID being generated when a cookieless session request is made with an expired sessionID.

Custom session identifiers
You can implement a custom class to supply and validate sessionID values by creating a class that inherits the sessionIDManager class and overriding the CreateSessionID and validate methods with your own custom implementations.
Session-state Events 
Asp.net provides two events to help you manage user sessions: the Session-OnStart event which is raised when a new session begins and the Session-OnEnd event which is raised when session is expires.

  1. Session-OnStart event: To handle this event you must add a subroutine named session-OnStart to the Global.asax file this subroutine run if a new session will start.
  2. Session-OnEnd event: To handle this event you must add a subroutine named Session-OnEnd to the Global.asax file this subroutine run if the abandon method has been called or when the session has expired.

How To: handle session events
Add the following subroutines to the Global.asax file 

C#
public void Session_OnStart() 
    {   
        //Add your code 
    }   

public void Session_OnEnd() 
    {   
        //Add your code 
    }



Session-state Modes
Session-state supports several different storage options for session data. They identified by a value in the SessionStateMode enumeration. To assign a mode set the mode attribute of the SessionState element in web.config

  1. In-Process Mode: In the default session state mode. This mode stores session state value in memory on the local web server. It is the only mode that supports the Session-OnEnd event.
  2. State server mode: In this mode session state values are stored in a process, which is separate from asp.net worker process or IIS application pool. Using this mode ensures that SessionState is preserved if the web application is restarted and also makes SessionState available to multiple web servers in a web farm. To use StateServer mode you must first be sure that the ASP.NET state services is running on the server used for session state store, this service is installed as a service when asp.net and the .net framework are installed.

The following example shows a configuration setting for StateServer mode where session state is stored on a computer named Nemo: 

C#
<configuration>   
    <system.web>     
        <sessionState mode="StateServer" stateConnectionString="tcpip=Nemo:42424" cookieless="false" timeout="20" />
    </system.web>
</configuration>


        
        3. Sql server mode: Sql server mode stores session state in a sql server database. Using this mode ensures that session state is preserved if the web application is
             restarted and also makes session state available to multiple web servers in a web farm. 
        4. Custom mode: Custom mode specifies that you want to store session state data using a custom session state store provide. When you configure your asp.net
            application with a mode of custom you must specify the type of the session state store provider using the providers sub element of the SessionState configuration
            element.

How To: Save values in session state
This example uses the HTTPSessionState object to save values within an individual session. 

C#
Session["FirstName"] = "Ahmed";
Session["LastName"] = "Rafie";



How To: Read values from session state
This example accesses the item property to retrieve the values from session state. 

C#
if (Session["FirstName"] != null)      
    {    
        string firstn = (string)Session["FirstName"];
    }



How To: Read values from application state
First you have to determine whether the application variables exist, and then convert the variable to the appropriate type when you access it. 

C#
if (Application["NumberOfVisitoes"] != null)        
    {   
        int total = (int)Application["NumberOfVisitoes"];
    }



You must cast from type object to the appropriate type when getting values out of session state

Conclusion
Depending on your application requirements you may want to consider an alternative to session state for storing information for each user. Asp.net provides several other options for persisting data within an application.

Comments