-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathCacheOutputAttribute.cs
More file actions
312 lines (252 loc) · 12.8 KB
/
CacheOutputAttribute.cs
File metadata and controls
312 lines (252 loc) · 12.8 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using WebApi.OutputCache.Core;
using WebApi.OutputCache.Core.Cache;
using WebApi.OutputCache.Core.Time;
namespace WebApi.OutputCache.V2
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class CacheOutputAttribute : ActionFilterAttribute
{
private const string CurrentRequestMediaType = "CacheOutput:CurrentRequestMediaType";
protected static MediaTypeHeaderValue DefaultMediaType = new MediaTypeHeaderValue("application/json") {CharSet = Encoding.UTF8.HeaderName};
/// <summary>
/// Cache enabled only for requests when Thread.CurrentPrincipal is not set
/// </summary>
public bool AnonymousOnly { get; set; }
/// <summary>
/// Corresponds to MustRevalidate HTTP header - indicates whether the origin server requires revalidation of a cache entry on any subsequent use when the cache entry becomes stale
/// </summary>
public bool MustRevalidate { get; set; }
/// <summary>
/// Do not vary cache by querystring values
/// </summary>
public bool ExcludeQueryStringFromCacheKey { get; set; }
/// <summary>
/// How long response should be cached on the server side (in seconds)
/// </summary>
public int ServerTimeSpan { get; set; }
/// <summary>
/// Corresponds to CacheControl MaxAge HTTP header (in seconds)
/// </summary>
public int ClientTimeSpan { get; set; }
private int? _sharedTimeSpan = null;
/// <summary>
/// Corresponds to CacheControl Shared MaxAge HTTP header (in seconds)
/// </summary>
public int SharedTimeSpan
{
get // required for property visibility
{
if (!_sharedTimeSpan.HasValue)
throw new Exception("should not be called without value set");
return _sharedTimeSpan.Value;
}
set { _sharedTimeSpan = value; }
}
/// <summary>
/// Corresponds to CacheControl NoCache HTTP header
/// </summary>
public bool NoCache { get; set; }
/// <summary>
/// Corresponds to CacheControl Private HTTP header. Response can be cached by browser but not by intermediary cache
/// </summary>
public bool Private { get; set; }
/// <summary>
/// Class used to generate caching keys
/// </summary>
public Type CacheKeyGenerator { get; set; }
// cache repository
private IApiOutputCache _webApiCache;
protected virtual void EnsureCache(HttpConfiguration config, HttpRequestMessage req)
{
_webApiCache = config.CacheOutputConfiguration().GetCacheOutputProvider(req);
}
internal IModelQuery<DateTime, CacheTime> CacheTimeQuery;
protected virtual bool IsCachingAllowed(HttpActionContext actionContext, bool anonymousOnly)
{
if (anonymousOnly)
{
if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
return false;
}
}
if (actionContext.ActionDescriptor.GetCustomAttributes<IgnoreCacheOutputAttribute>().Any())
{
return false;
}
return actionContext.Request.Method == HttpMethod.Get;
}
protected virtual void EnsureCacheTimeQuery()
{
if (CacheTimeQuery == null) ResetCacheTimeQuery();
}
protected void ResetCacheTimeQuery()
{
CacheTimeQuery = new ShortTime( ServerTimeSpan, ClientTimeSpan, _sharedTimeSpan);
}
protected virtual MediaTypeHeaderValue GetExpectedMediaType(HttpConfiguration config, HttpActionContext actionContext)
{
MediaTypeHeaderValue responseMediaType = null;
var negotiator = config.Services.GetService(typeof(IContentNegotiator)) as IContentNegotiator;
var returnType = actionContext.ActionDescriptor.ReturnType;
if (negotiator != null && returnType != typeof(HttpResponseMessage) && (returnType != typeof(IHttpActionResult) || typeof(IHttpActionResult).IsAssignableFrom(returnType)))
{
var negotiatedResult = negotiator.Negotiate(returnType, actionContext.Request, config.Formatters);
if (negotiatedResult == null)
{
return DefaultMediaType;
}
responseMediaType = negotiatedResult.MediaType;
if (string.IsNullOrWhiteSpace(responseMediaType.CharSet))
{
responseMediaType.CharSet = Encoding.UTF8.HeaderName;
}
}
else
{
if (actionContext.Request.Headers.Accept != null)
{
responseMediaType = actionContext.Request.Headers.Accept.FirstOrDefault();
if (responseMediaType == null || !config.Formatters.Any(x => x.SupportedMediaTypes.Any(value => value.MediaType == responseMediaType.MediaType)))
{
return DefaultMediaType;
}
}
}
return responseMediaType;
}
private bool IsNoCacheHeaderInRequest(HttpActionContext actionContext)
{
var cacheControl = actionContext.Request.Headers.CacheControl;
return cacheControl != null && cacheControl.NoCache;
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext == null) throw new ArgumentNullException("actionContext");
if (!IsCachingAllowed(actionContext, AnonymousOnly)) return;
var config = actionContext.Request.GetConfiguration();
EnsureCacheTimeQuery();
EnsureCache(config, actionContext.Request);
var cacheKeyGenerator = config.CacheOutputConfiguration().GetCacheKeyGenerator(actionContext.Request, CacheKeyGenerator);
var responseMediaType = GetExpectedMediaType(config, actionContext);
actionContext.Request.Properties[CurrentRequestMediaType] = responseMediaType;
var cachekey = cacheKeyGenerator.MakeCacheKey(actionContext, responseMediaType, ExcludeQueryStringFromCacheKey);
if (!_webApiCache.Contains(cachekey)) return;
if (IsNoCacheHeaderInRequest(actionContext)) return;
if (actionContext.Request.Headers.IfNoneMatch != null)
{
var etag = _webApiCache.Get<string>(cachekey + Constants.EtagKey);
if (etag != null)
{
if (actionContext.Request.Headers.IfNoneMatch.Any(x => x.Tag == etag))
{
var time = CacheTimeQuery.Execute(DateTime.Now);
var quickResponse = actionContext.Request.CreateResponse(HttpStatusCode.NotModified);
ApplyCacheHeaders(quickResponse, time);
actionContext.Response = quickResponse;
return;
}
}
}
var val = _webApiCache.Get<byte[]>(cachekey);
if (val == null) return;
var contenttype = _webApiCache.Get<MediaTypeHeaderValue>(cachekey + Constants.ContentTypeKey) ?? responseMediaType;
actionContext.Response = actionContext.Request.CreateResponse();
actionContext.Response.Content = new ByteArrayContent(val);
actionContext.Response.Content.Headers.ContentType = contenttype;
var responseEtag = _webApiCache.Get<string>(cachekey + Constants.EtagKey);
if (responseEtag != null) SetEtag(actionContext.Response, responseEtag);
var cacheTime = CacheTimeQuery.Execute(DateTime.Now);
ApplyCacheHeaders(actionContext.Response, cacheTime);
}
public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
if (actionExecutedContext.ActionContext.Response == null ||
!actionExecutedContext.ActionContext.Response.IsSuccessStatusCode ||
IsNoCacheHeaderInRequest(actionExecutedContext.ActionContext))
return;
if (!IsCachingAllowed(actionExecutedContext.ActionContext, AnonymousOnly)) return;
var cacheTime = CacheTimeQuery.Execute(DateTime.Now);
if (cacheTime.AbsoluteExpiration > DateTime.Now)
{
var httpConfig = actionExecutedContext.Request.GetConfiguration();
var config = httpConfig.CacheOutputConfiguration();
var cacheKeyGenerator = config.GetCacheKeyGenerator(actionExecutedContext.Request, CacheKeyGenerator);
var responseMediaType = actionExecutedContext.Request.Properties[CurrentRequestMediaType] as MediaTypeHeaderValue ?? GetExpectedMediaType(httpConfig, actionExecutedContext.ActionContext);
var cachekey = cacheKeyGenerator.MakeCacheKey(actionExecutedContext.ActionContext, responseMediaType, ExcludeQueryStringFromCacheKey);
//if (IsNoCacheHeaderInRequest(actionExecutedContext.ActionContext))
//{
// _webApiCache.Remove(cachekey);
//}
if (!string.IsNullOrWhiteSpace(cachekey) && !(_webApiCache.Contains(cachekey)))
{
SetEtag(actionExecutedContext.Response, CreateEtag(actionExecutedContext, cachekey, cacheTime));
var responseContent = actionExecutedContext.Response.Content;
if (responseContent != null)
{
var baseKey = config.MakeBaseCachekey(actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerType.FullName, actionExecutedContext.ActionContext.ActionDescriptor.ActionName);
var contentType = responseContent.Headers.ContentType;
string etag = actionExecutedContext.Response.Headers.ETag.Tag;
//ConfigureAwait false to avoid deadlocks
var content = await responseContent.ReadAsByteArrayAsync().ConfigureAwait(false);
responseContent.Headers.Remove("Content-Length");
_webApiCache.Add(baseKey, string.Empty, cacheTime.AbsoluteExpiration);
_webApiCache.Add(cachekey, content, cacheTime.AbsoluteExpiration, baseKey);
_webApiCache.Add(cachekey + Constants.ContentTypeKey,
contentType,
cacheTime.AbsoluteExpiration, baseKey);
_webApiCache.Add(cachekey + Constants.EtagKey,
etag,
cacheTime.AbsoluteExpiration, baseKey);
}
}
}
ApplyCacheHeaders(actionExecutedContext.ActionContext.Response, cacheTime);
}
protected virtual void ApplyCacheHeaders(HttpResponseMessage response, CacheTime cacheTime)
{
if (cacheTime.ClientTimeSpan > TimeSpan.Zero || MustRevalidate || Private)
{
var cachecontrol = new CacheControlHeaderValue
{
MaxAge = cacheTime.ClientTimeSpan,
SharedMaxAge = cacheTime.SharedTimeSpan,
MustRevalidate = MustRevalidate,
Private = Private
};
response.Headers.CacheControl = cachecontrol;
}
else if (NoCache)
{
response.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true };
response.Headers.Add("Pragma", "no-cache");
}
}
protected virtual string CreateEtag(HttpActionExecutedContext actionExecutedContext, string cachekey, CacheTime cacheTime)
{
return Guid.NewGuid().ToString();
}
private static void SetEtag(HttpResponseMessage message, string etag)
{
if (etag != null)
{
var eTag = new EntityTagHeaderValue(@"""" + etag.Replace("\"", string.Empty) + @"""");
message.Headers.ETag = eTag;
}
}
}
}