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

3.71 (7 votes)

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.

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 10972

4 Comments

- Aravind

Mike,
How to add Framework Services in ConfigureServices function?

- Aravind

Mike,
I tried the above, but session is not being stored in SQLServer. I have checked the connectionString and all seems to be fine. Not sure why it is not storing Session in Database. Am I missing something?

- Mike

@Aravind

You might want to try clearing your cookies for the localhost domain.

- Aravind

Mike,
I tried that too. But no luck! And I don't see any issue in the Middleware Services as well. Not sure what I am missing.

Thanks,

Recent Comments

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...

Harris Boyce 04/07/2017 04:17
In response to Razor Pages - The Elevator Pitch
As a developer of a couple "trivial" web pages applications used by non-profits that wouldn't have I...

Cyrus 28/06/2017 20:25
In response to Razor Pages - Getting Started With The Preview
.net core 2.0 preview 2: <a...

ojorma 17/06/2017 09:24
In response to Razor Pages - The Elevator Pitch
Finally I can say goodbye to webforms...