AddThis Social Bookmark Button

Print

Choosing the Right Session State Storage

by Mike Gunderloy
03/24/2003

You probably already know about the use of Session variables to store information in an ASP.NET session. More formally, the System.Web.UI.Page.Session property returns an instance of the System.Web.SessionState.HttpSessionState class. You can use this class to persist information as the user moves through your ASP.NET application. In C#, you might store a value in session state like this:

Programming ASP .NET

Related Reading

Programming ASP .NET
By Jesse Liberty, Dan Hurwitz


Session["Name"] = txtName.Text;

Later in the same session, you can retrieve the stored information:


if(Session["Name"] != null)
{
    lblName.Text = Session["Name"].ToString();
}

But have you ever thought about the server-side mechanics of session state? Where exactly is the stored information stored? It turns out that you have three choices for storing session state in an ASP.NET application:

  • In-process storage.
  • Session State Service.
  • Microsoft SQL Server.

In this article, I'll show you how to configure session state on your server. More importantly, I'll try to give you some guidance to help you make an intelligent choice between the alternatives.

In-Process Storage

The default location for session state storage is in the ASP.NET process itself. If you've got your own server set up with ASP.NET, you can see how this works:

  1. Create a new ASP.NET web application with two web forms, State1.aspx and State2.aspx. Make State1.aspx the default page.
  2. Put a TextBox (txtName), a Button (btnSubmit), and a Hyperlink (hlState2) on State1.aspx. Put a Label (lblName) on State2.aspx. Point the NavigateUrl of hlState2 to the State2.aspx page.
  3. Add some code for the button on State1.aspx:
    
    private void btnSubmit_Click(object sender, System.EventArgs e)
    {
        Session["Name"] = txtName.Text;
    }
    
  4. Add some code for the Load event on State2.aspx:
    
    private void Page_Load(object sender, System.EventArgs e)
    {
        if(Session["Name"] != null) 
        {
            lblName.Text = Session["Name"].ToString();
        }
    }
    
  5. Run the project. Enter a name in the TextBox control and click the button. Then click the HyperLink control to proceed to the second page. The label shows the name that you entered.
  6. Close the browser session. Run the project again to load the page into a fresh session. Enter a name and click the button, but do not click the hyperlink.
  7. Select Start-> Programs-> Administrative Tools-> Services on the computer where the web server for the project is located. Stop and restart the World Wide Web Publishing Service.
  8. Click the HyperLink control. The second page will load, but the name that you entered will not be in the label.

If you haven't changed the default configuration of ASP.NET, then session state information is stored in memory as part of the ASP.NET process itself. If you restart the WWW server (or if it crashes for some reason), all of this information is lost.

Session State Service

As an alternative to using in-process storage for session state, ASP.NET provides the ASP.NET State Service. The State Service gives you an out-of-process alternative for storing session state that is not tied quite so closely to ASP.NET's own process.

To use the State Service, you need to edit the sessionState element in your ASP.NET application's web.config file:


<sessionState
    mode="StateServer"
    stateConnectionString="tcpip=127.0.0.1:42424"
    sqlConnectionString=
     "data source=127.0.0.1;user id=sa;password="
    cookieless="false"
    timeout="20"
/>

You'll also need to start the ASP.NET State Service on the computer that you specified in the stateConnectionString attribute. The .NET Framework installs this service, but by default it's set to manual startup. If you're going to depend on it for storing session state, you'll want to change that to automatic startup by using the Services MMC plug-in in the Administrative Tools group.

If you make these changes, and then repeat the previous set of steps, you'll see slightly different behavior: session state persists even if you recycle the ASP.NET process.

There are two main advantages to using the State Service. First, it is not running in the same process as ASP.NET, so a crash of ASP.NET will not destroy session information. Second, the stateConnectionString that's used to locate the State Service includes the TCP/IP address of the service, which need not be running on the same computer as ASP.NET. This allows you to share state information across a web garden (multiple processors on the same computer) or even across a web farm (multiple servers running the application). With the default in-process storage, you can't share state information between multiple instances of your application.

The major disadvantage of using the State Service is that it's an external process, rather than part of ASP.NET. That means that reading and writing session state is slower than it would be if you kept the state in-process. And, of course, it's one more process that you need to manage. As an example of the extra effort that this can entail, there is a bug in the initial release of the State Service that allows a determined attacker to crash the ASP.NET process remotely. If you're using the State Service to store session state, you should install the patch from Microsoft Security Bulletin MS02-66, or install SP2 for the .NET Framework.

Microsoft SQL Server

The final choice for storing state information is to save it in a Microsoft SQL Server database. To use SQL Server for storing session state, you need to perform several setup steps:

  1. Run the InstallSqlState.sql script on the Microsoft SQL Server where you intend to store session state. This script will create the necessary database and database objects. The .NET Framework installs this script in the same folder as its compilers and other tools--for example, C:\WINNT\Microsoft.NET\Framework\v1.0.3705 on a Windows 2000 computer with the 1.0 version of the Framework.
  2. Edit the sessionState element in the web.config file for your ASP.NET application as follows:
    
    <sessionState
        mode="SQLServer"
        stateConnectionString="tcpip=127.0.0.1:42424"
        sqlConnectionString=
         "data source=SERVERHAME;user id=sa;password="
        cookieless="false"
        timeout="20"
    />
    
  3. Supply the server name, user name, and password for a SQL Server account that has access to the session state database in the sqlConnectionString attribute.

Like the State Service, SQL Server lets you share session state among the processors in a web garden or the servers in a web farm. But you also get the additional benefit of persistent storage. Even if the computer hosting SQL Server crashes and is restarted, the session state information will still be present in the database, and will be available as soon as the database is running again. That's because SQL Server, being an industrial-strength database, is designed to log its operations and protect your data at (almost) all costs. If you're willing to invest in SQL Server clustering, you can keep the session state data available transparently to ASP.NET even if the primary SQL Server computer crashes.

Like the State Service, SQL Server is slower than keeping session state in process. You also need to pay additional licensing fees to use SQL Server for session state in a production application. And, of course, you need to worry about SQL Server-specific threats such as the "Slammer" worm.

Making the Choice

As with many other things in the .NET world, the best starting point for adjusting your session state storage is simple: don't. For the average web site running on a single server, storing session state in-process gives the best performance, and it makes managing the site simpler.

When, then, should you choose a different alternative for session state? The two driving forces for these choices are scalability and reliability.

If you're moving to a web farm architecture to manage a heavy traffic load, then you have to abandon in-process session state (unless you invest in additional complexity at the TCP/IP level to make sure that all requests from a single user go to a single server). In this case, you should move to the State Service running on a central computer (probably one that's not directly serving web pages). The State Service gives you the performance of an in-memory cache for Session data, while not tying the user's session to a particular CPU or a particular computer.

On the other hand, if reliability is paramount, move to SQL Server for session state storage, even if your application is only running on a single CPU. Because of its transactional nature, SQL Server imposes additional overhead on storing and retrieving the data (as well as vastly higher costs!) as compared to the State Service. But the tradeoff is that you can make your session data very close to absolutely secure by storing it in SQL Server.

The bottom line is that ASP.NET's session state handling is vastly improved over what was available in classic ASP. With the advent of the State Service and the ability to store state in SQL Server, it's now possible to make your own tradeoffs between speed, scalability, and reliability for this potentially mission-critical data.

Mike Gunderloy is the lead developer for Larkware and author of numerous books and articles on programming topics.


Return to ONDotnet.com