Cookie – if not a cookie less to store Session ID.
e.g. ASP.NET_SessionId cookie gets created.
Cookie less – URL append with Session Id.
SQL Cache Dependencies,
File,
Query String Key
Storage Location
Data is stored in memory (in process),
Web Server.
Page (but can be modified to overwrite the storage mechanism to
store viewstate else where, esp. Session, Application, File or DataBase)
Data is stored in memory (in process),
Web Server
Data is stored in memory (in process),
Web Server
Can Store
Complex Objects & Any Data
e.g. DataSet
Any serializable class to ViewState.
e.g. Strings, DateTimes, and Integers
Page Output, Complex Object (e.g. DataSet),
Note
Anything that you add to ViewState must be added to the hidden __VIEWSTATE form field. If this field gets too big, it can have a significant impact on your page's performance.
ViewState is loaded after the Page InitComplete event, and ViewState is saved after the Page PreRenderComplete event. This means that you should not attempt to retrieve a value from ViewState before or during the InitComplete event. You also should not attempt to add a value to ViewState after the PreRenderComplete event.
Application state is little used in ASP.NET applications. In most cases, you should use the Cache object instead of Application state because the Cache object is designed to manage memory automatically.
In previous post we see what Session is, how to use it and what are all Modes of storing Session’s.
Now, we will see How to use State Server to store ASP.Net Session.
When you enable State Server Session state, Session state information is stored in a separate Windows NT Service. The Windows NT Service can be located on the same server as your web server, or it can be located on another server in your network.
If you store Session state in the memory of a separate Windows NT Service, then Session state information survives even when your ASP.NET application doesn't. For example, if your ASP.NET application crashes, then your Session state information is not lost because it is stored in a separate process.
Furthermore, you can create a web farm when you store state information by using a Windows NT Service. You can designate one server in your network as your state server. All the web servers in your web farm can use the central state server to store Session state.
You must complete the following two steps to use State Server Session state:
Start the ASP.NETState Service.
Configure your application to use the ASP.NETState Service.
You can start the ASP.NET State Service by opening the Services applet located at Start, Control Panel, Administrative Tools (see below image). After you open the Services applet, double-click the ASP.NETState Service and click Start to run the service. You also should change the Startup type of the service to the value Automatic so that the service starts automatically every time that you reboot your machine.
If you want to run the ASP.NETState Service on a separate server on your network, then you must edit a Registry setting on the server that hosts the ASP.NET State Service. By default, the ASP.NETState Service does not accept remote connections. To allow remote connections, execute RegEdit from a command prompt and set the following Registry key to the value 1:
After you start the ASP.NETState Service, you need to configure your ASP.NET application to use it. The web configuration file in shown below enables StateServerSessionState.
The web configuration file modifies three attributes of the sessionState element. First, the mode attribute is set to the value StateServer. Next, the stateConnectionString attribute is used to specify the location of the ASP.NETState Server. In above file, a connection is created to the local server on port 42424. Finally, the stateNetworkTimeout attribute is used to specify a connection timeout in seconds.
Note: You can configure the ASP.NETState Server to use a different port by modifying the following Registry value:
You need to stop and restart the ASP.NETState Service with the Services applet after making this modification.
Notice that the web configuration above includes a machineKey element. If you are setting up a web farm, and you need to use the same State Server to store Session state for multiple servers, then you are required to specify explicit encryption and validation keys. On the other hand, you don't need to include a machineKey element when the ASP.NETState Server is hosted on the same machine as your ASP.NET application.
Warning: Don't use the web configuration without modifying the values of both the decryptionKey and validationKey attributes. Those values must be secret.
After you complete these configuration steps, Session state information is stored in the ASP.NETState Server automatically. You don't need to modify any of your application code when you switch to out-of-process Session state.
In previous post we see what Session is, how to use it and what are all Modes of storing Session’s.
Now, we will see How to use SQL Server to store ASP.Net Session.
If you want to store Session state in the most reliable way possible, then you can store Session state in a Microsoft SQL Server database. Because you can set up failover SQL Server clusters, Session state stored in SQL Server should be able to survive just anything, including a major nuclear war.
You must complete the following two steps to enable SQL Server Session state:
Configure your database to support SQL Server Session state.
Configure your application to use SQL Server Session state.
You can use the aspnet_regsql tool to add the necessary tables and stored procedures to your database to support SQL Server Session state. The aspnet_regsql tool is located in the following path:
When you execute this command, a new database is created on your database server named ASPState. The ASPState database contains all the stored procedures used by Session state. However, by default, Session state information is stored in the TempDB database. When your database server restarts, the TempDB database is cleared automatically.
If you want to use SQL Server Session state with a failover cluster of SQL Servers, then you can't store Session state in the TempDB database. Also, if you want Session state to survive database restarts, then you can't store the state information in the TempDB database.
If you execute the following command, then Session state is stored in the ASPState database instead of the TempDB database:
aspnet_regsql -C "Data Source=YourServer;Integrated Security=True" -ssadd -sstype p
Notice that this command includes a -sstype p switch. The p stands for persistent. Session state that is stored in the ASPState database is called persistent Session state because it survives database server restarts.
Finally, you can store Session state in a custom database. The following command stores Session state in a database named MySessionDB:
aspnet_regsql -C "Data Source=YourServer;Integrated Security=True" -ssadd -sstype c –d MySessionDB
Executing this command creates a new database named MySessionDB that contains both the tables and stored procedures for storing Session state. Notice that the -sstype switch has the value c for custom. The command also includes a -d switch that enables you to specify the name of the new database.
If you want to remove the Session state tables and stored procedures from a server, then you can execute the following command:
Executing this command removes the ASPState database. It does not remove a custom Session state database. You must remove a custom database manually.
After you configure your database server to support Session state, you must configure your ASP.NET application to connect to your database. You can use the web configuration file to connect to a database named YourServer.
The sessionState element includes three attributes. The mode attribute is set to the value SQLServer to enable SQL Server Session state.
The second attribute, sqlConnectionString, contains the connection string to the Session state database.
Finally, the sqlCommandTimeout specifies the maximum amount of time in seconds before a command that retrieves or stores Session state times out.
Notice that the configuration file includes a machineKey element. If your Session state database is located on a different machine than your ASP.NET application, then you are required to include a machineKey element that contains explicit encryption and validation keys.
Warning: Don't use the web configuration file without modifying the values of both the decryptionKey and validationKey attributes.
If you select the option to store Session state in a custom database when executing the aspnet_regsql tool, then you need to specify the name of the custom database in your configuration file. You can use the web configuration file.
The sessionState element in the configuration file includes an allowCustomSqlDatabase attribute. Furthermore, the sqlConnectionString attribute contains the name of the custom database.
Enabling SQL Server session state has no effect on how you write your application code. You can initially build your application using in-process Session state and, when you have the need, you can switch to SQL Server Session state.
Like cookies, items stored in Session state are scoped to a particular user. You can use Session state to store user preferences or other user-specific data across multiple page requests.
Unlike cookies, Session state has no size limitations. If you had a compelling need, you could store gigabytes of data in Session state.
Furthermore, unlike cookies, Session state can represent more complex objects than simple strings of text. You can store any object in Session state. For example, you can store a DataSet or a custom shopping cart object in Session state.
When you use Session state, a session cookie named ASP.NET_SessionId is added to your browser automatically. This cookie contains a unique identifier. It is used to track you as you move from page to page.
When you add items to the Session object, the items are stored on the web server and not the web browser. The ASP.NET_SessionId cookie is used to associate the correct data with the correct user.
By default, if cookies are disabled, Session state does not work. You don't receive an error, but items that you add to Session state aren't available when you attempt to retrieve them in later page requests. (You learn how to enable cookieless Session state later in this section.)
By default, the ASP.NET Framework assumes that a user has left the website when the user has not requested a page for more than 20 minutes. At that point, any data stored in Session state for the user is discarded.
Using the Session Object
The main application programming interface for working with Session state is the HttpSessionState class. This object is exposed by the Page.Session, Context.Session, UserControl.Session, WebService.Session, and Application.Session properties. This means that you can access Session state from just about anywhere.
This HttpSessionState class supports the following properties (this is not a complete list):
CookieModeEnables you to specify whether cookieless sessions are enabled. Possible values are AutoDetect, UseCookies, UseDeviceProfile, and UseUri.
Count Enables you to retrieve the number of items in Session state.
IsCookieless Enables you to determine whether cookieless sessions are enabled.
IsNewSession Enables you to determine whether a new user session was created with the current request.
IsReadOnly Enables you to determine whether the Session state is read-only.
Keys Enables you to retrieve a list of item names stored in Session state.
Mode Enables you to determine the current Session state store provider. Possible values are Custom, InProc, Off, SqlServer, and StateServer.
SessionID Enables you to retrieve the unique session identifier.
Timeout Enables you to specify the amount of time in minutes before the web server assumes that the user has left and discards the session. The maximum value is 525,600 (1 year).
The HttpSessionState object also supports the following methods:
Abandon Enables you to end a user session.
Clear Enables you to clear all items from Session state.
Remove Enables you to remove a particular item from Session state.
The Abandon() method enables you to end a user session programmatically. For example, you might want to end a user session automatically when a user logs out from your application to clear away all of a user's session state information.
Handling Session Events
There are two events related to Session state that you can handle in the Global.asax file: the Session Start and Session End events.
The Session Start event is raised whenever a new user session begins. You can handle this event to load user information from the database. For example, you can handle the Session Start event to load the user's shopping cart.
The Session End event is raised when a session ends. A session comes to an end when it times out because of user inactivity or when it is explicitly ended with the Session.Abandon() method. You can handle the Session End event, for example, when you want to automatically save the user's shopping cart to a database table.
void Session_Start(object sender, EventArgs e)
{
//Code to handle Session at start of application
}
void Session_End(object sender, EventArgs e)
{
//Code to handle Session when it expires
}
Controlling When a Session Times Out
By default, the ASP.NET Framework assumes that a user has left an application after 20 minutes have passed without the user requesting a page. In some situations, you'll want to modify the default timeout value.
For example, imagine that you are creating a college admissions website and the website includes a form that enables an applicant to enter a long essay. In that situation, you would not want the user session to timeout after 20 minutes. Please, give the poor college applicants at least an hour to write their essays.
The disadvantage of increasing the Session timeout is that more memory is consumed by your application. The longer the Session timeout, the more server memory is potentially consumed.
You can specify the Session timeout in the web configuration file or you can set the Session timeout programmatically.
Using Cookieless SessionState
By default, Session state depends on cookies. The ASP.NET Framework uses the ASP.NET_SessionId cookie to identity a user across page requests so that the correct data can be associated with the correct user. If a user disables cookies in the browser, then Session state doesn't work.
If you want Session state to work even when cookies are disabled, then you can take advantage of cookieless sessions. When cookieless sessions are enabled, a user's session ID is added to the page URL.
Here's a sample of what a page URL looks like when cookieless sessions are enabled:
The strange-looking code in this URL is the current user's Session ID. It is the same value as the one you get from the Session.SessionID property.
You enable cookieless sessions by modifying the sessionState element in the web configuration file. The sessionState element includes a cookieless attribute that accepts the following values:
AutoDetect The Session ID is stored in a cookie when a browser has cookies enabled. Otherwise, the cookie is added to the URL.
UseCookies The Session ID is always stored in a cookie (the default value).
UseDeviceProfile The Session ID is stored in a cookie when a browser supports cookies. Otherwise, the cookie is added to the URL.
UseUri The Session ID is always added to the URL.
When you set cookieless to the value UseDeviceProfile, the ASP.NET Framework determines whether the browser supports cookies by looking up the browser's capabilities from a set of files contained in the following folder:
If, according to these files, a browser supports cookies, then the ASP.NET Framework uses a cookie to store the Session ID. The Framework attempts to add a cookie even when a user has disabled cookies in the browser.
When cookie less is set to the value AutoDetect, the framework checks for the existence of the HTTP Cookie header. If the Cookie header is detected, then the framework stores the Session ID in a cookie. Otherwise, the framework falls back to storing the Session ID in the page URL.
Configuring a SessionState Store
By default, Session state is stored in memory in the same process as the ASP.NET process. There are two significant disadvantages to storing Session state in the ASP.NET process.
You can set the Session state mode to any of the following values:
Off Disables Session state.
InProc Stores Session state in the same process as the ASP.NET process.
StateServer Stores Session state in a Windows NT process, which is distinct from the ASP.NET process.
SQLServer Stores Session state in a SQL Server database.
Custom Stores Session state in a custom location.
By default, the Session state mode is set to the value InProc. This is done for performance reasons. In-process Session state results in the best performance. However, it sacrifices robustness and scalability.
When you set the Session state mode to either StateServer or SQLServer, you get robustness and scalability at the price of performance. Storing Session state out-of-process results in worse performance because Session state information must be passed back and forth over your network.
Finally, you can create a custom Session state store provider by inheriting a new class from the SessionStateStoreProviderBase class. In that case, you can store Session state any place that you want. For example, you can create a Session state store provider that stores Session state in an Oracle or FoxPro database.