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

4.17 (6 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.

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

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

Jon 31/03/2016 21:36
In response to Exploring Prefix: A Free ASP.NET Profiling Tool
We had the exact same experience, finding multiple bugs in an application that we thought was pretty...

ranjith 31/03/2016 05:50
In response to A Better Way To Export Gridviews To Excel
Hello Mike. i am exporting from gridview, because i have some images in my gridview. but i am error...

Matt Watson 30/03/2016 22:19
In response to Exploring Prefix: A Free ASP.NET Profiling Tool
Glad you are loving it! Matt from Stackify...

Dmitry 28/03/2016 04:26
In response to Solved - The Microsoft.ACE.OLEDB.12.0 provider is not registered on the local machine
thank you about the VS 32-bit remark...

federico 26/03/2016 11:29
In response to Request.Form Is Empty When Posting To ASPX Page
thanks!....

Micheal 23/03/2016 00:58
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Thanks for the code. its pretty straightforward. worked for me on my first trial. Perfect!...

Francisco 22/03/2016 20:35
In response to ASP.NET MVC 5 with EF 6 - Working With Files
The post is very good, thanks...

Nick Brown 22/03/2016 13:53
In response to Adding A View
Hi, Many thanks for this tutorial, it's helping me get started with MVC. In VB (VS 2013) I get late...

ferry mae 22/03/2016 13:04
In response to Send form content by email in ASP.NET
do i need to change this? message.To.Add(new MailAddress("me@domain.com")); message.CC.Add(new you...

Keith 22/03/2016 12:02
In response to Creating a Connection String and Working with SQL Server LocalDB
As always worst explanation, but this time you rocked with plagiarism too .. huhh.. copied from Rick...