Caching options in ASP.NET Web API

1.6k views Asked by At

Why doesn't Web API come with caching features like MVC actions? Is it because these are HTTP based services so no state in between calls?

I have seen a few open sources like CacheCow and Strathweb, but not sure whom to pick and why? What are the best and standard options for caching with ASP.NET Web API?

1

There are 1 answers

3
JotaBe On

This is an extensive article that explains the principal options, and contains links to many more information:

EXPLORING WEB API 2 CACHING

It includes information about:

The poor man's implementation consist in:

  • implement a cache store that supports storing and retrieving values by key
  • generate a key from the request properties, like action parameters, method, headers, and so on, to generate a key
  • check if a value for that key is available in the cache store:

    • if it is available, return it
    • if it isn't generate it, store it and return it

    var result = cacheStore.GetValue(keyFromRequest); if (result == null) { result = MyClass.ExpensiveFunctionCall(params); cacheStore.Store(keyFromRequest, result); } return result;

The cache store can be, for example, a database, a memory cache like MemoryCache class, or a Redis server.

The evolution of this idea is to use MVC action filters to make this cache cheking automatic, or to use a fully implemented solution like the aforementioned CacheCow