Sdílet prostřednictvím


ASP.NET Session State

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; by default, the server retains no knowledge of variable values used during previous requests. As a result, building Web applications that need to maintain some cross-request state information (applications that implement shopping carts, data scrolling, and so on) can be a challenge. ASP.NET session state identifies requests received from the same browser during a limited period of time 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. ASP.NET session-state variables are easily set and retrieved using the Session property, which stores session variable values as a collection indexed by name. For example, the following code example creates the session variables FirstName and LastName to represent the first name and last name of a user, and sets them to values retrieved from TextBox controls.

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

ASP.NET stores session information in the memory space of the ASP.NET application by default. You can, optionally, store session information using a stand-alone service so that session information is preserved if the ASP.NET application is restarted, in a SQL Server so that session information is available to multiple Web servers in a Web farm (and also persists if the ASP.NET application is restarted), or in a custom data store. For more information, see Session-State Modes.

ASP.NET also provides several other options for persisting data within an application besides session state. For a comparison of each, see ASP.NET State Management Recommendations.

In This Section

Reference

  • System.Web.SessionState
    Provides classes and interfaces that enable storage of application data in session state.
  • Session
    Provides access to the session for the current HTTP request.
  • ASP.NET State Management
    Provides an overview of the methods available to store application state in ASP.NET applications.