Web API 2 output caching
Posted on 2015-03-20
When building REST APIs, a time comes when you want to cache data. You get more users or your app gets slower because of data accumulation.
In ASP.NET MVC, there’s a practical attribute called
OutputCacheAttribute which will send caching headers back to the client AND can also cache the results of queries
on the server for even more caching.
There’s no such attribute in Web API. So on my search to find a solution, I found StrathWeb’s Output Cache. It’s simple, effective and quite extendable.
It can be added directly on a method as such:
or even globally with a filter:
When adding a
ServerTimeSpan, an ETag is generated and it’s even easier to return 304 Not Modified later on.
It’s also extendable in many ways. For now, I’m only using the cache key generation via
ICacheKeyGenerator, which let’s me decide how to cache items.
In our APIs, we will generally cache results by the
Accept-Language header since the results vary. For other APIs, we plan on caching by user, so we will
create the key using the
So far, it doesn’t output the
Expires header, but it doesn’t seem necessary for the moment. I’ll have to read more about HTTP caching to make sure I understand
and then contribute to the project!