Configuring SQL Server For Session State In ASP.NET Core 1.0 MVC

This article looks at the steps required to enable SQL Server as a backing store for Session State in an ASP.NET Core 1.0 MVC application. It builds on my previous article which introduces how to configure and use session state in ASP.NET 5.

You would use SQL Server instead of server memory as a backing store for session state for a number of reasons, which mainly include scalability and reliability. If data is stored in a database, it is accessible from any server in a cluster or web farm, which enables system architects to more easily implement this kind of topology if it is required for sites that experience large increases in traffic. It also removes the load from the server's memory, freeing that up for more important tasks related to the actual processing of web pages. In addition, data stored in a database survives Application Pool recycles and server restarts.

In previous versions of ASP.NET, server memory is the default persistence mechanism for session state. In ASP.NET Core 1.0, there is no default storage for this data. You have to explicitly choose a package to provide storage. In my introductory article, I used memory, which is provided in a package called Microsoft.Extensions.Caching.Memory. The package which enables SQL Server caching is called Microsoft.Extensions.Caching.SqlServer, so you need to add that package to your project.json file along with Microsoft.AspNet.Session:

"Microsoft.Extensions.Caching.SqlServer": "1.0.0-rc1-final",
"Microsoft.AspNet.Session": "1.0.0-rc1-final"

You also need a database, and a connection string that points to it. You may want to use your existing application's database or set up a totally separate one just for storing session state. In either case, you only need one table, which can be named anything you like. In this example, I will use a database called SessionTest and the table in which session data will be stored is called Sessions.

Previous version of ASP.NET required a number of tables, stored procedures and jobs to manage the storage of session state. In ASP.NET Core 1.0, only one table is required. There are two ways in which you can generate the schema for the table so that it can be used by the Caching.SqlServer package. The first is to use a dnx command. Before you can do that, you need to install the command, which you do by executing the following command from a command prompt:

dnu commands install Microsoft.Extensions.Caching.SqlConfig

You should receive confirmation that the sqlservercache command was installed.

Once you have done that, you can execute the sqlservercache command that generates the appropriate table. It is in the format:

sqlservercache create <connectionstring> <schema> <table>

I am using a SQL Server 2012 LocalDb instance so the full command for that is

sqlservercache create "Server=(localdb)\MSSQLLocalDB;Database=SessionTest;Trusted_Connection=True;" "dbo" "Sessions"

If all goes well, you should receive confirmation that the table and index were successfully created.

The alternative approach to table creation is to execute the following CREATE TABLE script in SQL Server Management Studio against your chosen database:

CREATE TABLE [dbo].[Sessions](
    Id nvarchar(900) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL,
    Value varbinary(MAX) NOT NULL, 
    ExpiresAtTime datetimeoffset NOT NULL,
    SlidingExpirationInSeconds bigint NULL,
    AbsoluteExpiration datetimeoffset NULL,
    CONSTRAINT pk_Id PRIMARY KEY (Id));
CREATE NONCLUSTERED INDEX Index_ExpiresAtTime ON [dbo].[Sessions](ExpiresAtTime);

This is extracted and adapted from the source code in the ASP.NET/Caching repository.

You need to add a connection string to your appSettings.json file if you haven't already done so:

"Data": {
  "SessionConnection": {
    "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=SessionTest;Trusted_Connection=True;"
  }
}

Finally, you need to add Session and the appropriate Caching package to the application in its StartUp class. So you make them both available as services in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddSession();
    services.AddSqlServerCache(options =>
    {
        options.ConnectionString = Configuration["Data:SessionConnection:ConnectionString"];
        options.SchemaName = "dbo";
        options.TableName = "Sessions";
    });
    services.AddMvc();
}

Then you add Session middleware to the application pipeline in the Configure method - ensuring that it appears before MVC:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseSession();
    ...

For more information on the getting and setting of session values in controllers, please refer to my previous article on Session in ASP.NET Core 1.0.

Summary

This article walked through the steps required to enable SQL Server as a storage mechanism for session state in an ASP.NET Core 1.0 MVC application. It described two ways in which the appropriate table can be created in the target database, and showed how to enable and configure the necessary packages in the MVC application.