Click here to Skip to main content
15,921,212 members
Articles / Web Development / ASP.NET / ASP.NET Core

ASP.NET Core 2.0 Caching

Rate me:
Please Sign up or sign in to vote.
1.44/5 (2 votes)
5 Sep 2017CPOL1 min read 7.3K  
How to use distributed caching and Redis in ASP.NET Core. Continue reading...

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:

C#
public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = "..."; // Redis connection string
            });
        }

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

C#
public static class CachingExtensions
    {
        public static async Task SetObjectAsync<T>(
            this IDistributedCache cache, string key, T value)
        {
            await cache.SetStringAsync(key, JsonConvert.SerializeObject(value));
        }

        public static async Task<T> GetObjectAsync<T>(
            this IDistributedCache cache, string key)
        {
            var value = await cache.GetStringAsync(key);
            return value == null ? default(T) :
                                  JsonConvert.DeserializeObject<T>(value);
        }
    }

Create a middleware to write to the cache:

C#
public class WriteCachingMiddleware
    {
        private readonly RequestDelegate next;
        private readonly IDistributedCache cache;

        public WriteCachingMiddleware(
            RequestDelegate next,
            IDistributedCache cache)
        {
            this.next = next;
            this.cache = cache;
        }

        public async Task Invoke(HttpContext context)
        {
            await cache.SetObjectAsync("CurrentUser",
                new UserInfo { Username = "James", Email = "james@bond.com" });
            await this.next(context);
        }
    }

Create a middleware to read from the cache:

C#
public class ReadCachingMiddleware
    {
        private readonly RequestDelegate next;
        private readonly IDistributedCache cache;

        public ReadCachingMiddleware(
            RequestDelegate next,
            IDistributedCache cache)
        {
            this.next = next;
            this.cache = cache;
        }

        public async Task Invoke(HttpContext context)
        {
            var user = await cache.GetObjectAsync<UserInfo>("CurrentUser");
            await context.Response.WriteAsync($"{user.Username}, {user.Email}");
        }
    }

Discussion

Caching frequently used data can improve the performance of a web application. For application hosted on multiple servers, using distributed caching means the 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 provides 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.

This article was originally posted at https://tahirnaushad.com/2017/08/18/asp-net-core-caching

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --