Пример #1
0
        /// <summary>
        /// caches response before it is sent to client if it is a CacheableResponse or if the NegotationContext has the nancy-rapidcache
        /// header set.
        /// </summary>
        /// <param name="context"></param>
        private static void SetCache(NancyContext context)
        {
            if (context.Response is CachedResponse)
            {
                return;
            }

            if (context.Request.Query is DynamicDictionary dict)
            {
                if (DisableCache.Enabled && dict.ContainsKey(DisableCache.Key))
                {
                    return;
                }
            }

            string key = _cacheKeyGenerator.Get(context.Request);

            if (string.IsNullOrEmpty(key))
            {
                return;
            }

            if (context.Response.StatusCode != HttpStatusCode.OK)
            {
                _cacheStore.Remove(key);
                return;
            }

            var currentCache = _cacheStore.Get(key);
            var now          = DateTime.UtcNow;

            if (context.Response is CacheableResponse cacheableResponse)
            {
                if (currentCache == null || currentCache?.Expiration < now)
                {
                    _cacheStore.Set(key, context, cacheableResponse.Expiration);
                }
            }
            else if (context.NegotiationContext.Headers.ContainsKey(CacheHeader.ToLowerInvariant()))
            {
                var expiration = DateTime.Parse(context.NegotiationContext.Headers[CacheHeader],
                                                CultureInfo.InvariantCulture);

                context.NegotiationContext.Headers.Remove(CacheHeader);

                if (currentCache == null || currentCache?.Expiration < now)
                {
                    _cacheStore.Set(key, context, expiration);
                }
            }
        }