Exemple #1
0
        public async Task SetAsync(string key, IResponseCacheEntry entry, TimeSpan validFor)
        {
            object serializableEntry = null;

            if (entry is CachedResponse cachedResponse)
            {
                serializableEntry = SerializableCachedResponse.From(cachedResponse);
            }
            else if (entry is CachedVaryByRules varyByRules)
            {
                serializableEntry = SerializableCacheVaryByRules.From(varyByRules);
            }

            using var stream = new MemoryStream();

            using (var writer = new BinaryWriter(stream, Encoding.UTF8, true))
            {
                writer.Write(serializableEntry.GetType().Name);
                writer.Flush();
            }

            await JsonSerializer.SerializeAsync(stream, serializableEntry, serializableEntry.GetType());

            await cache.SetAsync(key, stream.ToArray(), new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = validFor
            });
        }
Exemple #2
0
        public static SerializableCachedResponse From(CachedResponse cachedResponse)
        {
            if (cachedResponse == null)
            {
                return(null);
            }

            var response = new SerializableCachedResponse
            {
                Created    = cachedResponse.Created,
                StatusCode = cachedResponse.StatusCode,
                Headers    = cachedResponse.Headers
                             .Select(header => new KeyValuePair <string, List <string> >(header.Key, header.Value.ToList()))
                             .ToList()
            };

            if (cachedResponse.Body != null)
            {
                using var stream = new MemoryStream();
                cachedResponse.Body.CopyTo(stream);
                response.Body = stream.ToArray();
            }

            return(response);
        }