How to Cache Output in ASP.NET Web API 2

ASP.NET Web API is a simple way to create a pretty nice and robust API.  I have a need for a simple API and ASP.NET fit the bill.  I created an API for my Space Weather application for all of my clients to connect to.  The API is pretty simple, it just feeds the clients objects in JSON for them to parse and bind to the UI.  After rebuilding my Azure virtual machine, I decided to add some caching to the results.  Since Web API doesn’t include an easy way to cache output like MVC did I had to find a solution. For me, the best (an easiest) solution was OutputCaching.  It’s super simple to set up.

Get the NuGet Package

Grab Filip W’s CacheOutput library.  I am using WebAPI 2.  I used package manager to get it:

This handles 90% of it.

Add the Attribute

The rest is just decorating your controllers just like you would for MVC.

In my example,  I am telling it to cache the results for both client and server-side for 600 sec (10 min).  There isn’t a whole lot of science behind choosing 10 minutes, and I could have written some fancy code to figure out when my scheduled job ran last but I wanted to keep it simple.


So, did it really work?  Let’s fire up Fiddler and find out. Hit your web endpoint, and take a look:

Sure enough, you can see the client is told to cache for a max of 600 and you can see the ETag letting you know that the server is caching.


So why do I choose to cache my output?  Simple.  I have a micro virtual machine on Azure and I didn’t want each and every web request to retrieve results from my database creating lots of churn and processing resulting in more disk activity and slower results.  Before going and implementing this I suggest you first evaluate your needs.  My needs are to return slow changing results to mobile clients as fast as possible without creating a lot of churn on the server.  I don’t want my customers to wait for results, especially if the result is the same.  My results change 4 times an hour and so caching this is the right thing to do in my scenario.  With that being said, I think this NuGet package help me meet this goal.

(Hanselman recommends Cache.Cow, although I like the simplicity and familiarity of decorating my Web API controllers with attributes using CacheOutput.)

5 thoughts on “How to Cache Output in ASP.NET Web API 2

  1. I have tried these but when i add de cacheOut the project throws an error saying that the versions of Newsoft.Json is wrong so i did a bindingRedirect in the web.config but after that the project doesn’t routes anymore.

    Why could that be ?

Leave a Reply

Your email address will not be published. Required fields are marked *