Configuring Redis Session State In ASP.NET Core

Introduction
 
Session is a feature of ASP.NET Core that enables us to save/store the user data. Sessions are of two types, namely InProc or In-memory and OutProc or Distributed session. If our session is in-memory and our Application is hosted on Web-Farm environment, we need to use sticky sessions to tie each session to a specific Server whereas OutProc session does not require sticky sessions and this is the most preferred way to use session in our Application.
 
There are mainly two ways to configure OutProc session: SQL Server Session State and Redis or Azure Redis Cache (Session State Server). In this article, we will learn about OutProc - Redis Session state in ASP.NET Core. The first step is to configure Redis.
 
Configure Redis
 
Redis is an open source and in-memory data store which is used as a distributed cache. We can install it locally and configure it. Also, we can configure an Azure Redis Cache. The easiest way to install Redis on a Windows machine is chocolatey. To install chocolatey on a local machine, run the command given below from PowerShell (with an administrative mode).
  1. PS C:\>iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))  
 
 
This command downloads the chocalatey installer for Windows and using the command given below, we can install Redis on the local machine.
  1. PS C:\>choco install redis-64  
  
 
Once Redis Server is installed, use the command given below, where we can start Redis Server.
  1. PS C:\>redis-server  
 
 
To check whether Redis Server starts working properly, we can ping this Server using Redis client. If the Server is working correctly, it returns “PONG” as response.
 
 
 
Configure Redis Session State
 
Now, Redis Server is ready to be used as a distributed session state. To use Redis as session state in ASP.NET Core, we need to add dependency of "Microsoft.Extensions.Caching.Redis.Core" and "Microsoft.AspNetCore.Session" in project.json file.
 
Project.json
  1. {  
  2.   "version""1.0.0-*",  
  3.   "buildOptions": {  
  4.     "preserveCompilationContext"true,  
  5.     "debugType""portable",  
  6.     "emitEntryPoint"true  
  7.   },  
  8.   "dependencies": {  
  9.       "Microsoft.AspNetCore.Server.Kestrel""1.0.0",    
  10.       "Microsoft.AspNetCore.Mvc""1.0.0",      
  11.       "Microsoft.AspNetCore.Session" : "1.0.0",  
  12.       "Microsoft.Extensions.Caching.Redis.Core""1.0.3"  
  13.    },  
  14.   "frameworks": {    
  15.       "netcoreapp1.0": {  
  16.         "dependencies": {    
  17.                 "Microsoft.NETCore.App": {    
  18.                     "type""platform",    
  19.                     "version""1.0.1"    
  20.                 }  
  21.             },    
  22.         "imports": ["dnxcore50","portable-net45+win8"]  
  23.       }  
  24.   }   
  25. }  
To enable Redis as a session state in the Application, we need to call "AddDistributedRedisCache" and "AddSession" methods from the ConfigureServices method of startup class.
 
Startup.cs 
  1. using System;  
  2. using Microsoft.AspNetCore.Builder;  
  3. using Microsoft.AspNetCore.Http;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5.   
  6. namespace WebApplication {  
  7.     public class Startup{  
  8.         public void ConfigureServices(IServiceCollection services)  
  9.         {  
  10.             services.AddDistributedRedisCache(options => {    
  11.                 options.Configuration = "localhost:6379";    
  12.                 options.InstanceName = "";    
  13.             });    
  14.               
  15.             services.AddSession(options => {   
  16.                 options.CookieName = "Test.Session";  
  17.                 options.IdleTimeout = TimeSpan.FromMinutes(60);   
  18.             });  
  19.               
  20.               
  21.             services.AddMvc();  
  22.         }  
  23.         public void Configure(IApplicationBuilder app){  
  24.             app.UseSession();  
  25.             app.UseMvc();              
  26.             app.Run(context => {  
  27.                 return context.Response.WriteAsync("Hello Readers!");  
  28.             });   
  29.         }  
  30.     }  
  31. }  
We can also verify how many keys are active on Redis Server by running the command given below on Redis client. 
  1. 127.0.0.1:6379> keys *  
 
 
The Redis Server stores the user session as key value pairs. The GUID shown in the figure above is a session Id of the user session, which is used as a key to store the user session. In an ASP.NET Core application, all the session values of an active session are stored as a value against Session Id.
 
Example
 
In the example given below, I have set my name into session in first request and retrieved the session value in another request.
  1. using Microsoft.AspNetCore.Http;    
  2. using Microsoft.AspNetCore.Mvc;    
  3. using Microsoft.Extensions.Caching.Distributed;    
  4.     
  5. public class HomeController : Controller    
  6. {    
  7.     [Route("home/index")]    
  8.     public IActionResult Index()    
  9.     {    
  10.         HttpContext.Session.SetString("name","Jignesh Trivedi");    
  11.         return View();    
  12.     }    
  13.     [Route("home/GetSessionData")]    
  14.     public IActionResult GetSessionData()    
  15.     {    
  16.         ViewBag.data = HttpContext.Session.GetString("name");    
  17.         return View();    
  18.     }    
  19. }   
Output



With Redis session state in ASP.NET Core, we can also create, use the session extension methods, and store complex object into the session, as described in my previous article.
 
Summary
 
This article described the steps required to configure Redis as a storage mechanism for session state in an ASP.NET Core MVC Application. The usage of Redis session state is slightly different from the classic ASP.NET Application.

Up Next
    Ebook Download
    View all
    Learn
    View all