Skip to content

Instantly share code, notes, and snippets.

@troyhunt
Created August 20, 2016 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troyhunt/be8d3e79693367c8aa69ae6f7303782c to your computer and use it in GitHub Desktop.
Save troyhunt/be8d3e79693367c8aa69ae6f7303782c to your computer and use it in GitHub Desktop.
A sliding cache implementation... that still expires after 1 second even with requests every 300ms
using System;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Caching;
using System.Web.Http;
namespace Web.Controllers
{
public class TestCacheController : ApiController
{
public HttpResponseMessage Get()
{
const string cacheKey = "MyCacheKey";
var cacheValue = HttpRuntime.Cache.Get(cacheKey);
// Value is not in cache, create the item and allow sliding expiration so it keeps extending
if (cacheValue == null)
{
HttpRuntime.Cache.Insert(cacheKey, string.Empty, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(1));
return Request.CreateResponse(HttpStatusCode.OK);
}
// Item was in cache so return forbidden
return Request.CreateResponse(HttpStatusCode.Forbidden);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment