Tuesday, December 23, 2008

ASP.NET Session State and Modes

ASP.NET Session State and Modes

The following terms are specific to this document:

Application Domain: A virtual process space within which ASP.NET is hosted and executed. On a Web server, it is possible to have multiple ASP.NET Web applications running inside a single process. Each ASP.NET application runs within its own application domain and is isolated from other ASP.NET applications that are running in separate application domains. An application domain has a unique identifier used as part of the identifying key on a state server when storing and retrieving session data.

ASP.NET: A Web server technology for dynamically rendering HTML pages using a combination of HTML, Javascript, CSS, and server-side logic.

ASP.NET State Server: Alternately, StateServer mode uses a stand-alone Microsoft Windows service to store session variables. Because this service is independent of Microsoft Internet Information Server (IIS), it can run on a separate server. You can use this mode for a load-balancing solution because multiple Web servers can share session variables. Although session variables are not lost if you restart IIS, performance is impacted when you cross process boundaries. .

InProc: In-Proc mode stores values in the memory of the ASP.NET worker process. Thus, this mode offers the fastest access to these values. However, when the ASP.NET worker process recycles, the state data is lost.

Session State: A feature for temporarily storing data associated with a browser session. Session state can be stored outside the process space of a session state client. The ASP.NET State Server is the default implementation for storing session state out of process.

URL: A uniform resource locator that identifies network-addressable endpoints. In the context of the ASP.NET State Server Protocol, a URL is used to identify a running instance of a state server implementation. The format of a state server URL is as specified in [RFC1738].

User Session Identifier: A unique identifier used as part of the identifying key when storing and retrieving session data.

Web Application Identifier: Each ASP.NET application running on a Web server is uniquely identified with a Web application identifier. The Web application identifier is the virtual path of the Web application on the Web server. A Web application identifier is used as part of the identifying key on a state server when storing and retrieving session data for a specific browser session.

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.

Alternatives to session state include the following:

  • Application state, which stores variables that can be accessed by all users of an ASP.NET application.
  • Profile properties, which persists user values in a data store without expiring them.
  • ASP.NET caching, which stores values in memory that is available to all ASP.NET applications.
  • View state, which persist values in a page.
  • Cookies.

The query string and fields on an HTML form that are available from an HTTP request.

Session Variables

Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext..::.Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object.

The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection. The following example shows how to create session variables in an ASP.NET page for the first and last name of a user, and set them to values retrieved from TextBox controls.

Visual Basic

Session("FirstName") = FirstNameTextBox.Text

Session("LastName") = LastNameTextBox.Text

C#

Session["FirstName"] = FirstNameTextBox.Text;

Session["LastName"] = LastNameTextBox.Text;

Session variables can be any valid .NET Framework type. The following example stores an ArrayList object in a session variable named StockPicks. The value returned by the StockPicks session variable must be cast to the appropriate type when you retrieve it from the SessionStateItemCollection.

Visual Basic

' When retrieving an object from session state, cast it to

' the appropriate type.

Dim stockPicks As ArrayList = CType(Session("StockPicks"), ArrayList)

' Write the modified stock picks list back to session state.

Session("StockPicks") = stockPicks

C#

// When retrieving an object from session state, cast it to

// the appropriate type.

ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.

Session["StockPicks"] = stockPicks;

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

Session Identifiers

Sessions are identified by a unique identifier that can be read by 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 value for that session is sent to the browser with the response.

By default, SessionID values are stored in a cookie. However, you can also configure the application to store SessionID values in the URL for a "cookieless" session.

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, the session is considered expired. Requests made with an expired SessionID value result in a new session.

Cookieless SessionIDs

By default, the SessionID value is stored in a non-expiring session cookie in the browser.

However, you can specify that session identifiers should not be stored in a cookie by
setting the cookieless attribute to true in the sessionState section of the Web.config file.
The following example shows a Web.config file that configures an ASP.NET application to cookieless session identifiers. 

<configuration>

<system.web>

<sessionState cookieless="true"

regenerateExpiredSessionId="true" />

</system.web>

</configuration>

ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page's URL. For example, the following URL has been modified by ASP.NET to include the unique session ID lit3py55t21z5v55vlm25s55:

http://www.example.com/(S(lit3py55t21z5v55vlm25s55))/orderform.aspx

When ASP.NET sends a page to the browser, it modifies any links in the page that use an application-relative path by embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as long as the user clicks links that have been modified in this manner. However, if the client rewrites a URL that is supplied by the application, ASP.NET may not be able to resolve the session ID and associate the request with an existing session. In that case, a new session is started for the request.

The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or virtual directory identifier. This enables ASP.NET to resolve the application name before involving the SessionStateModule in the request.

Session Modes

ASP.NET session state supports several storage options for session variables. Each option is identified as a session-state Mode type. 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 should 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.

Session Events

ASP.NET provides two events that help you manage user sessions. The Session_OnStart event is raised when a new session starts, and the Session_OnEnd event is raised when a session is abandoned or expires. Session events are specified in the Global.asax file for an ASP.NET application.

The Session_OnEnd event is not supported if the session Mode property is set to a value other than InProc, which is the default mode.

Session-State Modes

ASP.NET session state supports several different storage options for session data. Each option is identified by a value in the SessionStateMode enumeration. The following list describes the available session state modes:

  • InProc mode, which stores session state in memory on the Web server. This is the default.
  • StateServer mode, which stores session state in a separate process called the ASP.NET state service. This 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.
  • SQLServer mode stores session state in a SQL Server database. This 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.
  • Custom mode, which enables you to specify a custom storage provider.
  • Off mode, which disables session state.

You can specify which mode you want ASP.NET session state to use by assigning a SessionStateMode enumeration values to the mode attribute of the sessionState element in your application's Web.config file. Modes other than InProc and Off require additional parameters, such as connection-string values as discussed later in this topic. You can view the currently selected session state by accessing the value of the HttpSessionState..::.Mode property.

Inproc Mode

In-process mode is the default session state mode and is specified using the InProc SessionStateMode enumeration value. In-process mode stores session state values and variables in memory on the local Web server. It is the only mode that supports the Session_OnEnd event. For more information about the Session_OnEnd event, see Session-State Events.

Caution: If you enable Web-garden mode by setting the webGarden attribute to true in the processModel element of the application's Web.config file, do not use InProc session state mode. If you do, data loss can occur if different requests for the same session are served by different worker processes.

State Server Mode

StateServer mode stores session state in a process, referred to as the ASP.NET state service, that is separate from the ASP.NET worker process or IIS application pool. 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.

To use StateServer mode, you must first be sure the ASP.NET state service is running on the server used for the session store. The ASP.NET state service is installed as a service when ASP.NET and the .NET Framework are installed. The ASP.Net state service is installed at the following location:

systemroot\Microsoft.NET\Framework\versionNumber\aspnet_state.exe

To configure an ASP.NET application to use StateServer mode, in the application's Web.config file do the following:

  • Set the mode attribute of the sessionState element to StateServer.
  • Set the stateConnectionString attribute to tcpip=serverName:42424.

Note: To improve the security of your application when using StateServer mode, it is recommended that you protect your stateConnectionString value by encrypting the sessionState section of your configuration file. For details, see Encrypting Configuration Information Using Protected Configuration.

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

<configuration>

<system.web>

<sessionState mode="StateServer"

stateConnectionString="tcpip=SampleStateServer:42424"

cookieless="false"

timeout="20"/>

</system.web>

</configuration>

Note: Objects stored in session state must be serializable if the mode is set to StateServer. For information on serializable objects, see the SerializableAttribute class.

To use StateServer mode in a Web farm, you must have the same encryption keys specified in the machineKey element of your Web configuration for all applications that are part of the Web farm. For information on how to create machine keys, see article 313091, "How to create keys by using Visual Basic .NET for use in Forms authentication," in the Microsoft Knowledge Base at http://support.microsoft.com.

SQL Server mode

SQLServer 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.

Note: Objects stored in session state must be serializable if the mode is SQL Server. For information on serializable objects, see the SerializableAttribute class.

To use SQLServer mode, you must first be sure the ASP.NET session state database is installed on SQL Server. You can install the ASP.NET session state database using the Aspnet_regsql.exe tool, as described later in this topic.

To configure an ASP.NET application to use SQLServer mode, do the following in the application's Web.config file:

  • Set the mode attribute of the sessionState element to SQLServer.
  • Set the sqlConnectionString attribute to a connection string for your SQL Server database.

Note: to improve the security of your application when using SQLServer mode, it is recommended that you protect your sqlConnectionString value by encrypting the sessionState section of your configuration file. For details, see Encrypting Configuration Information Using Protected Configuration.

The following example shows a configuration setting for SQLServer mode where session state is stored on a SQL Server named "SampleSqlServer":

<configuration>

<system.web>

<sessionState mode=" SQLServer "

sqlConnectionString="Integrated Security=SSPI;data

source=SampleSqlServer;" />

</system.web>

</configuration>

Configuring Session State

Session state is configured by using the sessionState element of the system.web configuration section. You can also configure session state by using the EnableSessionState value in the @ Page directive.

The sessionState element enables you to specify the following options:

  • 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.
  • Supporting values that are based on the session Mode setting.

The following example shows a sessionState element that configures an application for SQLServer session mode. It sets the Timeout value to 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 value in the @ Page directive to false. The EnableSessionState value can also be set to ReadOnly to provide read-only access to session variables. Examples:

Save Values in Session State

Visual Basic

Dim firstName As String = "John"

Dim lastName As String = "Smith"

Dim city As String = "Seattle"

Session("FirstName") = firstName

Session("LastName") = lastName

Session("City") = city


C#

string firstName = "Jeff";

string lastName = "Smith";

string city = "Seattle";

Session["FirstName"] = firstName;

Session["LastName"] = lastName;

Session["City"] = city;

Read Values from Session State

Visual Basic

Dim firstName as String = CType(Session.Item("FirstName"), String)

Dim lastName as String = CType(Session.Item("LastName"), String)

Dim city as String = CType(Session.Item("City"), String)


C#

string firstName = (string)(Session["First"]);

string lastName = (string)(Session["Last"]);

string city = (string)(Session["City"]);

32 comments:

  1. Thank you so much! Just what I needed today! Excellent!

    ReplyDelete
  2. string firstName = (string)(Session["First"]);
    string lastName = (string)(Session["Last"]);
    string city = (string)(Session["City"]);

    Just a note here. Your casting a string to a string when you apply (string) in front of session. Session data usually doesn't keep it's type unless you've made some code for it to hold on to the data type.

    ReplyDelete
  3. im a beginner in asp.net and this article was very helpfully. thx

    ReplyDelete
  4. ... you can install the ASP.NET session state database using the Aspnet_regsql.exe tool, as described later in this topic...

    Where exactly?

    ReplyDelete
  5. Excellent article ,if you could give some simple examples about each session state mode using, that would be good any more!

    ReplyDelete
  6. Very informative article. good work, thanks

    ReplyDelete
  7. this article is very helpful

    ReplyDelete
  8. Good copy from the link :)
    http://msdn.microsoft.com/en-us/library/ms178586(VS.80).aspx

    ReplyDelete
  9. please mention your source, the msdn site from above!

    ReplyDelete
  10. basically i want that if we are making pages for administrator side and if dont want that if somebody enters the address of that page and that page opens up.we only want that only admin can access that page...what procedure should we follow.can you plz tell me.

    ReplyDelete
  11. Can we use one session in two webserver.

    ReplyDelete
  12. It is possible to store session in InProc mode when i redirect form my webserver to other webserver and i again come to my webserver and use that Session.

    ReplyDelete
  13. Good work.
    Very informative.:)

    ReplyDelete
  14. Dude, you stole this

    ReplyDelete
  15. Thanks, Great Material for MCTS Preparations.

    ReplyDelete
  16. This is a nice article..
    Its easy to understand ..
    And this article is using to learn something about it..

    c#, dot.net, php tutorial, Ms sql server

    Thanks a lot..!
    ri80

    ReplyDelete
  17. 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!!

    ReplyDelete
  18. Really nice article for freshers like me to understand Session State Management...
    Thanks!!!

    ReplyDelete
  19. THNANK YOU ! I want this code for my website

    ReplyDelete
  20. No, just kidding. But seriously, it screws with your creativity and expression. Most people are doubters and idea killers. These are two different types of blogs we're looking at.
    D-bal Max Reviews

    ReplyDelete
  21. Информация, которой вы делитесь, тоже хороша и интересна. Мне повезло прочитать эту статью

    Phối chó bull pháp

    Phối giống chó Corgi

    Phối chó Pug

    Dịch vụ phối giống chó Poodle

    Dịch vụ phối giống chó bull pháp

    ReplyDelete
  22. Tökezlediğiniz ve ayağa kalkıp(  taxi Nội Bài ) devam edemediğiniz gibi görünen zamanlar vardır, lütfen bazen( taxi sân bay nội bài rẻ nhất )  zorlukların üstesinden gelmenize yardımcı olacak, yaşamınızla(số điện thoại taxi nội bài ) ilgili iyi ( dịch vụ taxi đi nội bài chất lượng ) et. Aşağıdaki makale, yaşam hakkında 100'den fazla güzel kelime size tanıtır.

    ReplyDelete