ASP.NET Core – using Azure Cache for Redis

There are three distributed caching integrated with ASP.NET Core:

  • Distributed Memory Cache
  • Distributed SQL Server cache
  • Distributed Redis cache

Today we will learn how to use Distributed Redis Cache in ASP.NET Core application.

1 Add Microsoft.Extensions.Caching.Redis nuget package to your
ASP.NET Core application.

2 Modify ConfigureServices method in Startup.cs

services.AddDistributedRedisCache(options =>
{
    options.Configuration = redisConnectionString;
    options.InstanceName = "apiappmaster";
});

redisConnectionString is redis connection string
InstanceName can be any string

3 Inject IDistributedCache and you can use it now, for example:

private readonly IDistributedCache _cache;

public HomeController (IDistributedCache cache)
{
     _cache = cache;
}
string value = _cache.GetString("CacheData");

The redisConnectionString is the connection string to connect to a redis server, you can setup your own redis server or use Azure Cache for Redis.

Here we use Azure Cache for Redis

1 In Azure portal, create a new resource of Azure Cache for Redis

2 Once Azure Cache for Redis service was created, you can find connection string here:

Leave a comment