ASP.NET Core 2.0 Caching

Problem

How to use distributed caching and Redis in ASP.NET Core.

Solution

Starting from an empty project, add Redis services in ConfigureServices() method of Startup:

Create utility methods to set/get typed objects from the cache:

Create a middleware to write to the cache:

Create a middleware to read from the cache:

Discussion

Caching frequently used data can improve the performance of a web application. For application hosted on multiple servers, using distributed caching means application can access data regardless of the instance server. Caching should be considered an alternate to using Session State.

ASP.NET Core provides an abstraction over the distributed caching so that regardless of where the cache is physically stored (Redis, SQL), developers can interact using a uniform API. This interface is IDistributedCache and provide methods to set, get and remove cache data. Notice that it can be injected as dependency in your middleware, controllers etc.

The set/get methods of IDistributedCache work with byte[] but framework also provides extension methods to work with string values. These extension methods use Encoding.UTF8.GetBytes() and Encoding.UTF8.GetString() behind the scenes.

You could write your own extension methods to work with other strongly typed objects, as the above solution demonstrates.

I recommend considering Azure Redis Cache, it is really simple to setup and provides a lot of useful analytics to monitor usage.

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Perf.Caching

Leave a Reply