Output Caching on ASP.NET Web API

2013-09-10
Web API

Unfortunately ASP.NET Web API does not have output caching out of the box yet like ASP.NET MVC does with it’s OutputCache attribute. However there is a great library on github and nuget that gives you the same goodness easily!

From your NuGet Package Manager Console it’s as easy as;

PM&gt; Install-Package Strathweb.CacheOutput`</pre>
Then you can decorate your methods using something like;
<pre>`[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 100)]`</pre>
There are many other options so look at the readme on the [github page](https://github.com/filipw/AspNetWebApi-OutputCache) for those.

Now if you are calling your Web API using HttpClient you'll need to use WebRequestHandler as described in [HttpClient, it lives, and it is glorious](http://www.bizcoder.com/httpclient-it-lives-and-it-is-glorious). See below for an excerpt.
<pre>`public void UseDesktopHandlerToEnableCaching() 
{
    var clientHandler = new WebRequestHandler();
    clientHandler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable); // Enable private caching
    var httpClient = new HttpClient(clientHandler);
    var responseMessage = httpClient.GetAsync("http://www.bing.com").Result;
}

Comments: