Web API caching with CacheManager, CacheOutput and Redis

Customizable and extendable Web API caching with CacheManager, Strathweb.CacheOutput and Redis in the backend.

Source code for solution is available here https://github.com/mchudinov/WebApiCache



I like Strathweb.CacheOutput library. It gives cache attribute to Web API actions in a similar way as it is in ASP.NET MVC. To make cache flexible we use CacheManager. It is easy to change cache backed with CacheManager by just changing config options.

1. Install packages

2. Simple cache with CacheManager and Redis

The simple cache solution based on CacheManager and Redis is described here:
ASP.Net cache and session with Redis and CacheManager
and here is my blogpost about common cache interface and implementations: Common cache interface and implementations

3. Add implementation of WebApi.OutputCache.Core.Cache.IApiOutputCache

OuputCache has it’s own cache interface that must be implemented in order to customize backend.

I use implementation based on my CacheManager class. Read more about it in my blog post here ASP.Net cache and session with Redis and CacheManager

Add call in Configuration method in startup class:
config.CacheOutputConfiguration().RegisterCacheOutputProvider(() => new CustomCacheProvider());

4. Add custom key generator if needed

Add call in Configuration method in Startup class:
config.CacheOutputConfiguration().RegisterDefaultCacheKeyGeneratorProvider(() => new CustomCacheKeyGenerator());

Test the cache invalidation actually works with new key generation routine! Run some POST or PUT calls and watch that keys are deleted from cache. If they are not, then the custom generated keys are not good.

5. Configure Redis in .config file

6. Create WebAPI action with cache attributes and test cache

Add cache attributes. Cache must be used on GET methods, and invalidated (keys deleted) on POST,PUT and DELETE methods.

Now we can change cache backend for WebAPi by simply changing configuration.

Solution runs selfhosted WebAPI on localhost::8080 and a WebApiClient from a second console window.