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.

You might also like...

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

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

Sivu 19/10/2016 08:21
In response to Entity Framework Core TrackGraph For Disconnected Data
Oh that's very very very nice ! Thanks for the write up Mike, much appreciated for the taking the to...

Mark 12/10/2016 16:42
In response to ASP.NET Web Pages vNext or Razor Pages
Although "Web Pages" was removed from the roadmap, has it just been renamed to "Razor Pages"?...

Satyabrata 12/10/2016 09:20
In response to Entity Framework Core TrackGraph For Disconnected Data
Nice article. Please write more articles featuring ASP.Net web pages. Thank you...

Julian 26/09/2016 14:27
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Fantastic, many thanks Mike! Had got half way down this road before finding your article - saved...

Abolfazl Roshanzamir 14/09/2016 05:36
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Nice article. Thanke you so much ....

cyrus 02/09/2016 15:12
In response to ASP.NET Web Pages vNext or Razor Pages
I've got some news. As Damian stated in this link: https://github.com/aspnet/Mvc/issues/5208 “We...

Simon 01/09/2016 08:00
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Thanks Mike, nice post and exactly what I was looking for. Like you said, I think I'll opt to the...

dave 20/08/2016 14:57
In response to ASP.NET Web Pages vNext or Razor Pages
Do SimplemembershipProvider in viewpages is supported?...

Steven 18/08/2016 04:40
In response to Entity Framework Code First and Stored Procedures
Can you provide the directives (using statements) you're using for EF7 example?...

yousaid 17/08/2016 22:08
In response to ASP.NET Web Pages vNext or Razor Pages
Increasingly, learning a Microsoft tool is no longer worth the return on investment. Too many tools...