Caching in .NET Core for Fun and Profit 2

I’ve been giving the following talk at Meetups, User Groups, and at Tech Conferences.

Ever wonder how you might use caching to improve the performance and speed of your website? Are you looking to improve the user experience for your web application? We’ll discuss the ins and outs of caching in .NET Core, when and where to apply a caching strategy, and considerations for each scheme.


What is caching?

In computing, a cache is a hardware or software component that stores data so future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation, or the duplicate of data stored elsewhere.

– Wikipedia


Benefits of caching

So, why would you want to implement caching? To boost performance, improve the user experience, and to save money.

Save server roundtrips

If the content that you are delivering never changes or rarely changes, it might be beneficial to let the client cache the information on their machine.

Decrease response time

Sometimes poor performance can be blamed on network latency. Many times this is out of our control for external/public facing websites. Of course you can look into CDNs or hosting your application in different regions around the world. Another potential win is to lessen the time spent on your servers. If your application requires multiple or frequent roundtrips to the database, it may be possible to move the data closer by utilizing some method of caching.

Improve performance

By using a caching mechanism to minimize round trips to the database, for instance, your server(s) will have more resources available to fill more requests and process more information. This can often have a positive impact on performance of an application.

Save money

In there era of cloud computing we’re often charged by computing cycles. A poorly designed application and for that matter a well designed application can squander money by not utilizing a good caching strategy.


Best Practices

Caching can be abused. I’ve had to work on a legacy application that was suffering as a result of their caching strategy. In this application nearly the entire database was loaded into the server’s cache upon login of a new user. Each time a new user would login the cache was invalidated and loaded again. Don’t do this. While appreciate what the prior developers were trying to do, it ended up causing more problems than it solved. Evaluate your application to see how, when, and why to cache.

Cache early, cache often

If you’re working on an application that has a set of lookup data that is used often, but rarely changes, this is a good candidate for caching. Think list of States and State Abbreviations. If could make sense to add a list of warehouses or fulfillment facilities to cache if they are used often enough and are unlikely to change. In these scenarios try to determine the best time in the application lifecycle to populate the cache. Can you add to cache during application start? Would it be acceptable to the first user of the system to incur the cost of populating the cache? There is a small penalty to populating cache, but the benefit of using the cached values should far outweigh said penalty.

Caches should be relatively small

That said, caches should be small. Don’t pull in the entire database if you simply need a list of available shirt sizes. Keep the size and quantity of caches down to a minimum to be useful and manageable.

Expire Cache

If the data being cached has the potential to be modified make sure that there is a way to invalidate or expire the cache. It may be perfectly acceptable to cache product data for up to 30 minutes. Many caching mechanisms will have the ability to invalidate, update, clear, or delete items from the cache. Be sure to use these appropriately.


Let’s look at some code!

We’ll look at a variety of caching mechanism available to us in .NET Core. Examples include ResponseCache, MemoryCache, and touching on a simple way to use Redis for caching.

Response Cache

To get started let’s look at caching on the client. By adding the ResponseCache attribute to an ActionResult you can effectively tell the client’s browser that it is safe to cache on the client side.

In order to use the ResponseCache attribute you must first install the following NuGet packages:


We also need to modify Startup.cs to include Response Caching:

No we can add the ResponseCache attribute to our controller:

This will add a value to the Response Header that tells the client browser it is safe to store the page in cache for 20 seconds.


Memory Cache

In prior versions of .NET there was an OutputCache attribute that you could apply. This would store the cache on the web server. This has not made it in .NET Core. Instead, we’ll be relying on MemoryCache.

To use MemoryCache you must first install the following NuGet packages:


We now need to add MemoryCache to Startup.cs:

Now we can implement MemoryCache in our controller:

Here you can see that if the cache contains data with the supplied key then the cached data is returned. If no cache value is contained with the given key then data is retrieved from the service, added to the cache, and then returned.



In the following example we’ll be placing our session data in Redis. First, we’ll need to install a Redis server locally using NuGet and ensure it is running:

We next need to install the following NuGet packages:

We now need to add MemoryCache to Startup.cs:

Now we can interact with Redis from our controller:

With Redis we get the additional benefit of distributed caching. That means that if we had multiple web-servers there wouldn’t be any issues with often encountered with non-sticky sessions, etc.



The code examples provide here and at GitHub are used as part of a presentation. There are specific items used for teaching purposes that you should avoid in your own code (hard-coded keys, in-memory filtering, etc.)


Further Reading

Response Caching and In Memory Caching in ASP.NET Core 1.0
Introduction to in-memory caching in ASP.NET Core
Distributed Cache using Redis and ASP.NET Core

Take a look at the sample project on GitHub.


Edit: Steve Smith was kind enough to share a post via Twitter the last time I gave this talk that he wrote a while ago that pairs nicely with this one.


A Microsoft MVP, John has been a professional developer since 1999. He has focused primarily on web technologies and has experience with everything from PHP to C# to AngularJS to SignalR. Clean code and professionalism are particularly important to him, as well as mentoring and teaching others what he has learned along the way.

Please Consider Sharing This Post:

  • Shane Ray

    Also make sure not to use local cache in a distributed environment due to negative side effects. I would also add cache should be supplemental and only used to increase performance it should not be required to achieve performance. One other thing I have seen where caching can have negative side effects is in parallel loops. Parallelism is added when caching is not in the picture, then with caching the calls are going so fast that the CPU overhead of the parallelism negatively effects performance.

    • Hi Shane. All good points. Thanks for your comment!