Created
August 20, 2016 21:10
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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