faqfront.com
ASP.NET SQL Server 2005 Session State
Author: Sacha Bye
A cookbook solution on how to configure and use SQL Server 2005 as your ASP.NET 2.0 Session State repository. Examples are provided using both SQL and Windows Authentication for securing and accessing the database.
Why Use SQL Server as a Session State repository?
The default in process or "InProc" session state storage for ASP.NET retains session information in memory on the IIS server. This works fine, so long as you only have a single web server. When scaling out an ASP.NET application across two or more servers in a web farm or two or more instances in a web garden, the server affinity imposed by in process session storage can become problematic. Server affinity is a term used to describe the effect of binding a user's session to a particular web server. If a user's session is bound to a single web server then all HTTP requests from that particular user must be routed to the same server after a session is established. This is sometimes known as "sticky sessions". While sticky sessions can be supported through both hardware and software load balancing solutions, this is not the recommended approach for maximizing performance.

ASP.NET supports two methods of storing session information outside of the web server: State Server and SQL Server. State Server allows you to store session information in memory managed by a separate process. This process, aspnet_state.exe, can run on a separate machine from your web servers. Although a Sate Server is a viable option, it does represent a single point of failure for your application. If the State Server goes down, your scaled out application goes with it. Additionally, if the State Server does go down and then comes back up (i.e. a reboot) all sessions previously stored will have been lost.

Using SQL Server to store session state has all of the benefits of a State Server but none of the drawbacks. You can avoid having a single point of failure by applying typical SQL Server availability strategies, mirroring and clustering being two examples. In addition, SQL Server provides persistent storage – even if all of the database servers go down, the stored sessions would be available again once the database was brought back online.
A Note on Performance
Using either a State Server or SQL Server for session storage does incur a performance penalty when compared to in process storage. Generally speaking, you can estimate 10 to 15 percent overhead when using a State Server and a 15 to 25 percent overhead when using SQL server compared to in process Session State storage. You can reduce the performance hit incurred with SQL Server by pinning the tables in memory but whether or not this is advisable is highly dependent upon your situation. Either way, pinning tables is beyond the scope of this document.
What does this solution look like?
Let's take a walk though the HTTP request/response cycle in a load balanced web server environment that uses SQL Server for Session State storage.
  1. The client makes an HTTP request from their browser.
  2. The client's HTTP request is received by the load balancer. The load balancer makes a decision as to which web server to redirect the request to.
  3. The web server receiving the HTTP request makes a request to the SQL session server to retrieve the user's session.
  4. The SQL session server responds with the serialized session objects.
  5. The web server de-serializes the session objects and completes processing the user's request.
  6. The web server then serializes the user's session objects and sends them to the SQL session server for storage.
  7. With the session information stored in the database, the web server sends the HTTP response directly to the requesting client.
Building the Session Database
Creating the session database in SQL Server is easy! ASP.NET can build it for you using the aspnet_regsql.exe tool. This tool is installed with the .NET Framework and can be found at C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe. This tool supports a number of options and is used for more than just creating session state databases. The options we need to be concerned with are shown below. Please note: all of these options are case sensitive.

-ssadd
This option tells aspnet_regsql to create a database to support the storage of session information in SQL Server.

-sstype [Type of Session Database: t|p|c]
There are three types of approaches to session state storage in SQL Server:

Temporary (t): session data is stored in the "tempdb" database and stored procedures for managing session data are stored in a database called "ASPState". Data is not persisted when using this approach – if you restart SQL Server all session related data will be lost.

Persisted (p): both the session data and the stored procedures to manage it are stored in a database called "ASPState". Data is persisted to disk using this option.

Custom (c): both the session data and the stored procedures to manage it are stored in a database with a custom name. See the –d option for specifying a database name.

-S [Server Name]
This option specifies the server name for your SQL Server instance.

-d [Database Name]
This option is only used, and is required, if you specify a "custom" value for sstype (-sstype c).

-U [SQL User Name]
Use this option to specify a SQL Server Login name if connecting to the SQL Server instance using SQL Authentication. Not required if using the –E option.

-P [SQL User Password]
Use this option to specify a SQL Server Login password if connecting to the SQL Server instance using SQL Authentication. Not required if using the –E option.

-E
Use this option instead of –U and –P to connect to the SQL Server using Windows Authentication.
Building the Session Database (Examples)
This document assumes the use of the .NET Framework v2.0, and a custom database name of "App_SessionState". All instructions will work equally well with both the p and c options for –sstype, just be sure to replace instances of the database name "App_SessionState" with "ASPState".
Creating a SQL Server Session Database Using Windows Authentication
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727> aspnet_regsql.exe -ssadd -sstype c -d App_SessionState  -S [SQL Server Name] –E
Creating a SQL Server Session Database Using SQL Authentication
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727> aspnet_regsql.exe -ssadd -sstype c -d App_SessionState  -S [SQL Server Name] –U [SQL User Name] – P [SQL User Password]
Securing the Session State Database using SQL Authentication
Securing the Session State database consists of two steps: setting an appropriate owner and creating an account for the application to use when getting or setting session data. Depending on which account you used when creating the database you may or may not need to change the owner. The script shown below assumes that you want the "sa" account to own the database. The script below will additionally create a new SQL login called "appUser" with the password "Password1234" and assign all the roles required to access and use the Session State database.
Script to Secure the Session State Database using SQL Authentication
USE App_SessionState;

DECLARE @dbOwner varchar(100);
DECLARE @dbUser varchar(100);
DECLARE @dbUserPass varchar(100);

-- Configure Script Here!
SET @dbOwner = 'sa';
SET @dbUser = 'AppSessionUser';
SET @dbUserPass = 'Password1234';

-- Ensure that the database owner is an appropriate admin account
EXEC sp_changedbowner @loginame=@dbOwner;

-- Create the new application account
EXEC sp_addlogin @loginame=@dbUser

-- Set the default database for the new account
EXEC sp_defaultdb @loginame=@dbUser, @defdb='App_SessionState';

-- Grant access to the Session State database to the dbUser account
EXEC sp_grantdbaccess @loginame=@dbUser;

-- Create a new Role for stored procedure execution
-- Note: This only works in SQL Server 2005
CREATE ROLE db_executor
GRANT EXECUTE TO db_executor

-- Assign read, write, and execute permissions to the dbUser account
EXEC sp_addrolemember @rolename='db_datareader', @membername=@dbUser;
EXEC sp_addrolemember @rolename='db_datawriter', @membername=@dbUser;
EXEC sp_addrolemember @rolename='db_executor', @membername=@dbUser;
Securing the Session State Database using Windows Authentication
As with SQL Authentication, securing the Session State database with Windows Authentication consists of two steps: setting an appropriate owner and creating an account for the application to use when getting or setting session data. The script shown below assumes that you want an account named "Domain\DatabaseOwner" to own the database. The script below will additionally create a new Windows login for SQL Server called "Domain\AppSessionUser" and assign all the roles required to access and use the Session State database. The Windows accounts must exist prior to running this script.
Script to Secure the Session State Database using Windows Authentication
USE App_SessionState;

DECLARE @dbOwner varchar(100);
DECLARE @dbUser varchar(100);
DECLARE @dbUserPass varchar(100);

-- Configure Script Here!
SET @dbOwner = 'Domain\DatabaseOwner';
SET @dbUser = 'Domain\AppSessionUser';
SET @dbCatalog = 'App_SessionState';

-- Ensure that the database owner is an appropriate admin account
EXEC sp_changedbowner @loginame=@dbOwner;

-- Create the new application account
EXEC sp_grantlogin @loginame=@dbUser

-- Set the default database for the new account
EXEC sp_defaultdb @loginame=@dbUser, @defdb=@dbCatalog;

-- Grant access to the Session State database to the dbUser account
EXEC sp_grantdbaccess @loginame=@dbUser;

-- Create a new Role for stored procedure execution
-- Note: This only works in SQL Server 2005
CREATE ROLE db_executor
GRANT EXECUTE TO db_executor

-- Assign read, write, and execute permissions to the dbUser account
EXEC sp_addrolemember @rolename='db_datareader', @membername=@dbUser;
EXEC sp_addrolemember @rolename='db_datawriter', @membername=@dbUser;
EXEC sp_addrolemember @rolename='db_executor', @membername=@dbUser;
Using the SQL Session State Database from an ASP.NET 2.0 Application
To successfully use SQL Server as your session state repository in an ASP.NET 2.0 application you must make some simple updates to the Web.config file. The mode attribute of the sessionState element must be set to “SQLServer” and the sqlConnectionString attribute must specify the appropriate connection string for your SQL Server instance. Examples of the sessionState element configured for both SQL Authentication and Windows Authentication schemes are shown below. As always, please note that the sessionState element must occur within the system.web element of your web.config file.
Settings for the sessionState element in web.config using SQL Authentication
<sessionState
    mode="SQLServer"
    sqlConnectionString="data source=server;initial catalog=App_SessionState;user id=AppSessionUser;password=Password1234"
    cookieless="false"
    timeout="20" />
Settings for the sessionState element in web.config using Windows Authentication
<sessionState
    mode="SQLServer"
    sqlConnectionString="data source=server;initial catalog=App_SessionState;trusted_connection=true"
    cookieless="false"
    timeout="20" />
 
© 2007 Access E.I.S. Inc. All Rights Reserved