JumpStart # 45 – Redis Cache based Session State in ASP.Net Core MVC Application

In this Jumpstart, we are going to see how to use Redis Distributed Cache Server as Session store for an ASP.Net Core Application. There are multiple advantages in having a distributed cache storage (in this case it is Redis Cache) acting as Session store. Sessions can be shared across multiple applications and also between multiple servers in a cluster. Redis is also capable of supporting different data types and it is faster than SQL Server (because of its in-memory nature). Redis also supports cluster for scaling and persistence to disk (data will not be lost on server restarts).

NOTE: Updated this tutorial on 2/26/2017 with MSBuild based Dotnet SDK.

Create an ASP.Net Core Application using VS 2017. I am using following version of Dotnet SDK which is based on MSBuild/CSProj (remember that previous versions of ASP.Net Core are based on Project.json/XProj.).

image

Lets get started by installing Redis on local machine. First install Chocolatey (a package manager for Windows). Open Command Line prompt in Administrator mode and run below command.

@powershell -NoProfile -ExecutionPolicy Bypass -Command “iex ((New-Object System.Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1′))” && SET “PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin”

image

Now install Redis with below command.

choco install redis-64

image

Run Redis server with below command.

image

We are going to use AddDistributedRedisCache. To use Redis Cache, we need to add following packages dependencies.

<ItemGroup>
  <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
  <PackageReference Include="Microsoft.AspNetCore" Version="1.0.3" />
  <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.2" />
  <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.0" />
  <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.0.1" />
  <PackageReference Include="Microsoft.Extensions.Caching.Redis" Version="1.1.0" />
  <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.0.1" />
  <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.0.1" />
</ItemGroup>

Now lets configure ASP.Net Core Application with Redis Cache in Startup class under ConfigureServices method. Configuration setting is Redis connection string to the server on which it is installed and InstanceName is going to an identifier which is used to identify cache keys uniquely for an application.

services.AddDistributedRedisCache(options =>
{
    options.Configuration = "localhost";
    options.InstanceName = "RedisInstance";
});

services.AddSession(options =>
{
    options.CookieHttpOnly = true;
    options.CookieName = ".ASPNetCoreSession";
    options.IdleTimeout = TimeSpan.FromMinutes(10);
    options.CookiePath = "/";
});

As the last step of configuration, lets add Session service to our HTTP Pipeline as shown below in Configure method of Startup class. One important point to be remembered is that UseSession()should be added to pipeline before UseMvc().

app.UseSession();

To demonstrate usage of session, lets create (or update if they already exist) below actions in HomeController.

public IActionResult Index()
{
    HttpContext.Session.SetString("User", "Rami");
    return Json(true);
}

public IActionResult About()
{
    var userContent = HttpContext.Session.GetString("User");
    return Json(userContent);
}

Now using Postman tool, lets make a request to Index action. We should see below response.

image

Lets make a request to About Action. We should see below response with data being loaded from session and sent back in JSON format.

image

If we run the redis-cli from command line prompt, we can check the Redis key value pairs. To check the key we just inserted, use keys * command. Then to check the value associated with the key, we have to use hgetall key (hgetall is used to get the value of type HASH, typically ASP.Net Core storing the values in Redis in HASH data type).

image

That’s it for now. Happy Coding and Stay Tuned!!!

You may also like...