This repository has been archived by the owner on Nov 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
MemoryResponseCache.cs
93 lines (83 loc) · 3.12 KB
/
MemoryResponseCache.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
namespace Microsoft.AspNetCore.ResponseCaching.Internal
{
public class MemoryResponseCache : IResponseCache
{
private readonly IMemoryCache _cache;
public MemoryResponseCache(IMemoryCache cache)
{
if (cache == null)
{
throw new ArgumentNullException(nameof(cache));
}
_cache = cache;
}
public IResponseCacheEntry Get(string key)
{
var entry = _cache.Get(key);
var memoryCachedResponse = entry as MemoryCachedResponse;
if (memoryCachedResponse != null)
{
return new CachedResponse
{
Created = memoryCachedResponse.Created,
StatusCode = memoryCachedResponse.StatusCode,
Headers = memoryCachedResponse.Headers,
Body = new SegmentReadStream(memoryCachedResponse.BodySegments, memoryCachedResponse.BodyLength)
};
}
else
{
return entry as IResponseCacheEntry;
}
}
public Task<IResponseCacheEntry> GetAsync(string key)
{
return Task.FromResult(Get(key));
}
public void Set(string key, IResponseCacheEntry entry, TimeSpan validFor)
{
var cachedResponse = entry as CachedResponse;
if (cachedResponse != null)
{
var segmentStream = new SegmentWriteStream(StreamUtilities.BodySegmentSize);
cachedResponse.Body.CopyTo(segmentStream);
_cache.Set(
key,
new MemoryCachedResponse
{
Created = cachedResponse.Created,
StatusCode = cachedResponse.StatusCode,
Headers = cachedResponse.Headers,
BodySegments = segmentStream.GetSegments(),
BodyLength = segmentStream.Length
},
new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = validFor,
Size = CacheEntryHelpers.EstimateCachedResponseSize(cachedResponse)
});
}
else
{
_cache.Set(
key,
entry,
new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = validFor,
Size = CacheEntryHelpers.EstimateCachedVaryByRulesySize(entry as CachedVaryByRules)
});
}
}
public Task SetAsync(string key, IResponseCacheEntry entry, TimeSpan validFor)
{
Set(key, entry, validFor);
return Task.CompletedTask;
}
}
}