Maintaining user session on msdeploy in ASP.NET Core (in SQL Server)

Using TeamCity, Bitbucket and msdeploy, I have been able to develop a satisfactory CI process for my web apps. However, I found that whenever an application was deployed to production, the user sessions would expire. Initially, it was not a big issue, but as the number of users grew so did the issue. We want to make the deployment process as smooth and as painless for our uses as possible.

IIS persists user sessions in the application memory. Whenever the application pool is restarted, all the memory was wiped clean and the information was lost. It took me a while to research the solution, but I eventually tracked the solution down to services.AddDataProtection(). I strongly recommend reading Microsoft's Configure ASP.NET Core Data Protection as it offers a valuable insight into potential security breaches which might occur as a result of applying the changes in this article.

Using file system storage

Out of the box, Microsoft offers to store keys in PersistKeysToAzureBlobStorage, PersistKeysToFileSystem and PersistKeysToRegistry.

File system would have been sufficient for what I needed. Unfortunately my hosting provider restricted access to the file system; hence preventing my from applying this approach.

Using SQL Server

EF code-first model class

Add the class to your DbContext and run Add-Migration and Update-database.

Repository for the model

Add the repository. Note the inheritance from IXmlRepository.

Just remember to point to your own DbContext. You may wish to create a separate context (either db or schema) to handle these. .NET Core SQL DataProtection Key Storage Provider using Entity Framework by Longing to Know covers this in more detail.

Configure Startup

Please note, this is only a very simple. You may want to add some encryption to your data (you column datatype will change).