How to use Redis Cache in ASP.NET Core

This post shows you how to use Redis Cache in ASP.NET Core using C# Code.

The Redis Cache is an open source, in-memory data structure store and used as a database to cache and message broker.

The first thing you need to install the Redis Cache to your project, you can use Manage Nuget Packages or Run the Nuget command line in visual studio as the following.

Install-Package Microsoft.Extensions.Caching.Redis

Open your Startup.cs class, then add a configuration that will allow your website to support Redis Cache.

public void ConfigureServices(IServiceCollection services)
    services.AddDistributedRedisCache(option =>
        option.Configuration = "";
        option.InstanceName = "master";

Remark: is local IP, you can change the IP in the real world

Create a web API controller to practice the demo as shown below

public class HomeController : Controller
    private readonly IDistributedCache _distributedCache;

    public HomeController(IDistributedCache distributedCache)
        _distributedCache = distributedCache;

    public async Task<string> Get()
        var cacheKey = "C-SharpCode";
        var existing = _distributedCache.GetString(cacheKey);
        if (!string.IsNullOrEmpty(existing))
            return "Fetch data from cache instead from database";
            existing = DateTime.UtcNow.ToString();
            //You will get data from your database, then set to redis cache
            _distributedCache.SetString(cacheKey, existing);
            return "Your data from database or redis cache";

The IDistributedCache interface has async methods, so you should use these methods in all possible scenarios.

This interface allows storing string values or byte. If you want to serialize an object and store the whole object, you can serialize it to bytes and save it as bytes, or serialize it to JSON format, and save it as a string if you prefer.