Friday, February 20, 2009

Saving sessions to sql database

Using sessions on a web site is very flexible. Normally the session states are saved on the webserver. But in some occasions you need to be sure that the session state is preserved if the web application is restarted, or when sessions are used on multiple web servers in a web farm.

In this article I will describe how to configure and use sessions by saving them to an SQL Server database.

Note! There are however some limitations with saving sessions to database:
-Firstly you can't save primitive data types like int, string, double etc. You can only save custom objects.
-Secondly the custom objects that you save have to be serialized before you save them to the session.
-Thirdly you have to deserialize the data when retrieving the session.

Creating the ASPState database

Start creating the ASPState database by running a script in command prompt.

1. Open a command prompt.
2. Go to folder C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

3. Type in the following command: aspnet_regsql.exe -S sqlservername -E -ssadd -sstype p (where sqlservername is the name of your sql instance)



4. Click Enter.
5. The database should now have been creted.

An alternative way to generate the ASPState database is to run the script InstallSqlState.sql which also resides under folder
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727. (Note! This is however not recommended.)

Changing the web.config

1. You also need add/change your web.config file. Add the sessionstate tag as below:



2. sqlservername is the name of your sql instance. Also note that I have put a timeout for the session to 35 minutes.

Saving and loading sessions to database

1. All custom classes/objects that needs to be saved as a session to the database needs to be serializable classes. This is simply done by adding the [Serializable] keyword before the class declaration.



2. We will also need to create two methods that serialize and deserialize our custom class.



3. Now we can save and load the session with the following code:



For complete source code click here.

No comments:

Post a Comment

get a counter