Skip to main content

Distributed session management in ASP.NET Core MVC Application

Introduction

In this article, I am going to explain what are simple steps if you want to use distributed sessions in order to make your ASP.NET Core application load balanced.

Assumption

I am assuming that you already have created default project for ASP.NET core MVC app using visual studio.

Sessions

Session object is used in order to save or store user data for configurable amount of time. It uses dictionary on server side to store data and session id can be used as key to manage data back and forth.

There are two types of sessions:
1. In Memory
2. Distributed

In case of in memory session, session are stored in memory of a server and if you are using two servers, other server will not have access to it as it is saved in memory of server 1. It is discouraged for load balanced applications.

While distributed sessions are stored in centralized place where both servers have access and it is considered to be more useful and reliable mechanism to store data in large applications. We will use it for this tutorial as we are also doing load balancing.
We are going to use SQL Server database to store session data and will implement Distributed SQL Server Cache.
Lets get started

project.json

Create a new file at root of project and name is project.json and copy below content inside it.

{
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": {
"version": "1.0.0-preview2-final",
"imports": "portable-net45+win8+dnxcore50"
},
"Microsoft.Extensions.Caching.SqlConfig.Tools": "1.0.0-preview2-final"
},
"dependencies": {},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.Session": "1.0.0",
"Microsoft.Extensions.Caching.SqlServer": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0"
},
"imports": "dnxcore50"
}
}
}

Run dotnet restore command in package manager console.

Create database and table to store session

Once SQLconfig tools are installed, now we need to create empty database in SQL server and after creation of database, we require table in our database in order to store session data. Following package manager console command can be used to create table and index.

dotnet sql-cache create "{Your connection string}" dbo SessionDataStore
You can find details of SQL server distributed cache here

Data Protection

Deployment of application to web farm requires Distributed caching and Data protection.
You need to add a data protection key file and need to keep same file in both servers in order to retrieve session data created by other server. Or you can keep protection key file in shared location from where both server can read.

You can find details of data protection here


Startup.cs

Open startup.cs file and copy below code in ConfigureServices method.

services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo("Path of protection file, typically shared drive"))
.SetDefaultKeyLifetime(TimeSpan.FromDays(100))
.SetApplicationName("Your app name");
services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = "SQL Server database connection string";
options.SchemaName = "dbo";
options.TableName = "SessionDataStore";
});
services.AddSession(options => {
options.Cookie.Name = "Test.Session";
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
services.AddAuthentication("CookieAuthenticationScheme")
.AddCookie("CookieAuthenticationScheme", options =>
{
options.LoginPath = "/Account/Login";
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.SlidingExpiration = true;
}); services.AddMvc();

Add below code in Configure method


app.UseSession();
app.UseMvc();

Now in your controller files you can use Session Class methods to save and retrieve session values from distributed Cache.

Save data to session

HttpContext.Session.SetString("StudentName","Lavister Todies");

Get data from session

var name = HttpContext.Session.GetString("StudentName"); All done !!!

Comments

Popular posts from this blog

ASP.NET CORE File Upload along with Complex Object with AJAX

Problem Area: In one of my project, my requirement was to Post File along Complex object to server using AJAX. I could not find ready made solution targeting both things in a single project so I decided to share this solution with you guys to try it out as well. HTML: <input type="file" id="uploadEditorImage" />  <input type="button" id="upload" value="upload" onclick="uploadImage()" /> Javascript: function uploadImage()     {         var userObj = {};         userObj.userId = "123456";         var serializedObj = JSON.stringify(userObj);         var formData = new FormData();         formData.append('file', $('#uploadEditorImage')[0].files[0]);         formData.append('vm', serializedObj );         var _urlAction = '@Url.Action("Upload", "Home")';         $.ajax({   ...

Publish Paid Android Apps on Google Play Store

Good news for the all the Android developers!  Other new countries that can now publish paid apps are: Pakistan, Jordan, Lebanon, Oman, Puerto Rico, Qatar, And Venezuela. These countries can now publish paid Android apps and games on the Google Play Store. This news just came in earlier this week after Google allowed support for another 7 countries who can now sell apps. Previously, Android users in Pakistan were only able to purchase and download paid apps but it was a hassle for a developer who wanted to make money by selling his app/game. For those developers who are new to this and want to get started, visit the  Google Play Developer Console . There is a $25 registration fees for the first time when you sign up, so make sure you have a credit card with you. To check out other countries from where you can publish Android apps  — there are more than 60 countries now. Check them

How to Run WhatsApp on Computer

WhatsApp is one of the coolest applications we have in our smat phones. Everyone does not have a smart phone and they still want to use WhatsApp. Today I will describe that how can you do that. BlueStacks solved this problem nicely. This software helps you to install and use Android applications on your WhatsApp. You can download this application from  bluestacks.joydownload.com/‎ Steps to configure WhatsApp: Install BlueStacks Player. Enter your Gmail account details. (It will link you to play store) You will see the list of applications on the main dashboard. Click on WhatsApp. Configure WhatsApp using your mobile number. Congratulations. You have successfully installed and configure WhatsApp on your computer.