Export (0) Print
Expand All

Session State Overview

ASP.NET session state enables you to store and retrieve values for a user as the user navigates the different ASP.NET pages that make up a Web application. HTTP is a stateless protocol, meaning that your Web server treats each HTTP request for a page as an independent request; the server retains no knowledge of variable values used during previous requests. ASP.NET 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.

ASP.NET session state is enabled by default for all ASP.NET applications.

Alternatives to session state include application state (see the Application property), which stores variables that can be accessed by all users of an ASP.NET application; the System.Web.Profile namespace, which persists user values in a data store without expiring them using a time-out; the System.Web.Caching namespace, which stores frequently used values in memory that is available to all ASP.NET applications; ASP.NET System.Web.UI.WebControls, which persist control values in the ViewState; Cookies; the QueryString; and fields on an HTML form that are available from an HTTP POST using the Form collection. See ASP.NET State Management Recommendations for a comparison of different state-management options.

Session Variables

Session variables are stored in a SessionStateItemCollection that is exposed through the System.Web.HttpContext.Session property. The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by simply referring to the session variable by name. You do not need to declare a session variable or explicitly add it to the collection. For example, the following code example creates session variables for the first and last name of a user and sets them to values retrieved from TextBox controls.

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

By default, session variables can be any valid .NET type. For example, the following code example stores an ArrayList of values in a session variable named "StockPicks." Note that the value returned by the "StockPicks" session variable must be cast as the appropriate type upon retrieval from the SessionStateItemCollection.

NoteNote

When you use a session-state mode other than InProc, the session-variable type must be either a primitive .NET type or serializable, because the session-variable value is stored in an external data store. For more information, see Session-State Modes.

// When retrieving an object from session state, cast it as 
// the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;

Session Identifiers

Sessions are identified by a unique session identifier that can be read using the SessionID property. When session state is enabled for an ASP.NET application, each request for a page in the application is examined for a SessionID value sent from the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID for that session is sent to the browser with the response.

SessionID values are stored in a cookie, by default, but you can also configure your application to store SessionID values in the URL for a "cookieless" session. For more information, see Session Identifiers.

A session is considered active as long as requests continue to be made with the same SessionID value. If the time between requests for a particular session exceeds the specified time-out value in minutes, then the session is considered expired. Requests made with an expired SessionID value result in a new session being started.

Session Events

ASP.NET provides two events that 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 a session is abandoned or expires. Session events are specified in the Global.asax file for an ASP.NET application. Note that the Session_OnEnd event is not supported if the session Mode is set to a value other than InProc, which is the default mode.

NoteNote

If the Global.asax file or Web.config file for an ASP.NET application is modified, the application will be restarted and any values stored in application state or session state will be lost. Be aware that some anti-virus software can update the last-modified date and time of the Global.asax or Web.config file for an application.

For more information, see Session-State Events.

Session Modes

ASP.NET session state supports several different storage options for session variables. Each option is identified as a session-state Mode. The default behavior is to store session variables in the memory space of the ASP.NET worker process. However, you can also specify that session state be stored in a separate process, in a SQL Server database, or in a custom data source. If you do not want session state enabled for your application, you can set the session mode to Off.

For more information, see Session-State Modes.

Configuring Session State

Session state is configured using the sessionState element of the system.web configuration section. You can also configure session state using the EnableSessionState page directive.

The sessionState element allows you to specify the mode in which the session will store data, the way in which session identifier values are sent between the client and the server, the session Timeout value, and supporting values based on the session Mode. For example, the following sessionState element configures an application for SQLServer session mode, with a Timeout of 30 minutes, and specifies that session identifiers are stored in the URL.

<sessionState mode="SQLServer"
  cookieless="true "
  regenerateExpiredSessionId="true "
  timeout="30"
  sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;"
  stateNetworkTimeout="30"/>

You can disable session state for an application by setting the session-state mode to Off. If you want to disable session state for only a particular page of an application, you can set the EnableSessionState page directive to false. Note that the EnableSessionState page directive can also be set to ReadOnly to provide read-only access to session variables.

Concurrent Requests and Session State

Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (that is, using the same SessionID value), then the first request received gains exclusive access to the session information and the second request will execute once the first request completes, or until the exclusive lock on the information is freed due to the first request exceeding the lock timeout. If the EnableSessionState page directive is set to ReadOnly, then a request for the read-only session information does not result in an exclusive lock on the session data. Read-only requests for session data may still have to wait for a lock gained by a read-write request for session data to clear.

See Also

Community Additions

ADD
Show:
© 2014 Microsoft