/// <summary> /// Check to see if we have a cache entry - if we do, see if it has expired or not, if it /// hasn't then return it, otherwise return null. /// </summary> /// <param name="context">Current context.</param> /// <returns>Response or null.</returns> Response CheckCache(NancyContext context) { var cacheKey = context.GetRequestFingerprint(); var cachedSummary = _cache.Get<ResponseSummary>(ResponseCachePartition, cacheKey); return cachedSummary.HasValue ? cachedSummary.Value.ToResponse() : null; }
/// <summary> /// Adds the current response to the cache if required Only stores by Path and stores the /// response in a KVLite cache. /// </summary> /// <param name="context">Current context.</param> void SetCache(NancyContext context) { if (context.Response.StatusCode != HttpStatusCode.OK) { return; } object cacheSecondsObject; if (!context.Items.TryGetValue(ContextExtensions.OutputCacheTimeKey, out cacheSecondsObject)) { return; } int cacheSeconds; if (!int.TryParse(cacheSecondsObject.ToString(), out cacheSeconds)) { return; } // Disable further caching, as it must explicitly enabled. context.Items.Remove(ContextExtensions.OutputCacheTimeKey); // The response we are going to cache. We put it here, so that it can be used as // recovery in the catch clause below. var responseToBeCached = context.Response; try { var cacheKey = context.GetRequestFingerprint(); var cachedSummary = new ResponseSummary(responseToBeCached); _cache.AddTimed(ResponseCachePartition, cacheKey, cachedSummary, _cache.Clock.UtcNow.AddSeconds(cacheSeconds)); context.Response = cachedSummary.ToResponse(); } catch (Exception ex) { const string errMsg = "Something bad happened while caching :-("; LogManager.GetLogger<CachingBootstrapper>().Error(errMsg, ex); // Sets the old response, hoping it will work... context.Response = responseToBeCached; } }