A simple filter bringing caching options, similar to MVC’s "OutputCacheAttribute" to Web API ApiControllers. This code was inspired by Filip W’s aspnetwebapi-outputcache. I found his blog post and started playing around with his code. I rapidly found myself asking for more flexibility and for a different behavior. I needed to cache my service responses until a specific moment in time. In my case, I need to cache until 17h45 every day.
Get the code @ https://github.com/brisebois/aspnetwebapi-outputcache
This code has been pulled into filipw / AspNetWebApi-OutputCache and is available through Nuget, run the following command in the Package Manager Console.
PM> Install-Package Strathweb.CacheOutput -Pre
CacheOutput
Using CacheOutput: This will cache for a specific amount of time in seconds. The caching periods for the client and server are independent.
[CacheOutput(120, 0)] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } [CacheOutput(0, 60, false, false)] public string Get(int id) { return "value"; }
Where the first parameter indicates caching on the server side in seconds, the second indicates caching on the client side in seconds, the third decides whether to cache for anonymous users only, the fourth decides whether the origin server require revalidation of a cache entry on any subsequent use when the cache entry becomes stale.
Variation: CacheOutputUntil
Using CacheOutputUntil: is used to cache data until a specific moment in time.
// CacheOutput until TODAY @ 17:45:00 & don't pay attention to query strings // [CacheOutputUntil(Hour, // Minutes, // Seconds, // AnonymousOnly, // excludeQueryStringFromCacheKey: true)] [CacheOutputUntil(17, 45, 00, true, excludeQueryStringFromCacheKey: true)] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // CacheOutput until TODAY @ 17:45:00 [CacheOutputUntil(17, 45)] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // CacheOutput until 2012/01/01 00:00:00 [CacheOutputUntil(2012, 01, 01)] public string Get(int id) { return "value"; } // CacheOutput until (This year)/01/01 00:00:00 [CacheOutputUntil(01, 01)] public string Get(int id) { return "value"; } // CacheOutput until (This year)/(this month)/01 00:00:00 [CacheOutputUntil(01)] public string Get(int id) { return "value"; } // CacheOutput until 2012/01/01 17:45:00 [CacheOutputUntil(2012, 01, 01, 17, 45)] public string Get(int id) { return "value"; }
Nice Job Alex. I’ll use that one in my Azure cache control.
LikeLike
Could you make a video tutorial on youtube. I tried yo use this but when the Json.Net gets updated, the web api stops routing.
LikeLike
Hi, this code is pretty old now. Try pulling the latest NuGet package.
LikeLike