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).
- 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.
- PS C:\>choco install redis-64
Once Redis Server is installed, use the command given below, where we can start 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
- {
- "version": "1.0.0-*",
- "buildOptions": {
- "preserveCompilationContext": true,
- "debugType": "portable",
- "emitEntryPoint": true
- },
- "dependencies": {
- "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
- "Microsoft.AspNetCore.Mvc": "1.0.0",
- "Microsoft.AspNetCore.Session" : "1.0.0",
- "Microsoft.Extensions.Caching.Redis.Core": "1.0.3"
- },
- "frameworks": {
- "netcoreapp1.0": {
- "dependencies": {
- "Microsoft.NETCore.App": {
- "type": "platform",
- "version": "1.0.1"
- }
- },
- "imports": ["dnxcore50","portable-net45+win8"]
- }
- }
- }
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
- using System;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace WebApplication {
- public class Startup{
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDistributedRedisCache(options => {
- options.Configuration = "localhost:6379";
- options.InstanceName = "";
- });
-
- services.AddSession(options => {
- options.CookieName = "Test.Session";
- options.IdleTimeout = TimeSpan.FromMinutes(60);
- });
-
-
- services.AddMvc();
- }
- public void Configure(IApplicationBuilder app){
- app.UseSession();
- app.UseMvc();
- app.Run(context => {
- return context.Response.WriteAsync("Hello Readers!");
- });
- }
- }
- }
We can also verify how many keys are active on Redis Server by running the command given below on Redis client.
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.
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Caching.Distributed;
-
- public class HomeController : Controller
- {
- [Route("home/index")]
- public IActionResult Index()
- {
- HttpContext.Session.SetString("name","Jignesh Trivedi");
- return View();
- }
- [Route("home/GetSessionData")]
- public IActionResult GetSessionData()
- {
- ViewBag.data = HttpContext.Session.GetString("name");
- return View();
- }
- }
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.