-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathCacheOutputAttribute.cs
More file actions
351 lines (281 loc) · 14.2 KB
/
CacheOutputAttribute.cs
File metadata and controls
351 lines (281 loc) · 14.2 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
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.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, AllowMultiple = false, Inherited = true)]
public class CacheOutputAttribute : FilterAttribute, IActionFilter
{
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; }
/// <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; }
/// <summary>
/// Comma seperated list of HTTP headers to cache
/// </summary>
public string HeadersToInclude { get; set; }
private MediaTypeHeaderValue _responseMediaType;
// cache repository
private IApiOutputCache _webApiCache;
protected virtual void EnsureCache(HttpConfiguration config, HttpRequestMessage req)
{
_webApiCache = config.CacheOutputConfiguration().GetCacheOutputProvider(req);
}
internal IModelQuery<DateTime, CacheTime> CacheTimeQuery;
readonly Func<HttpActionContext, bool, bool> _isCachingAllowed = (ac, anonymous) =>
{
if (anonymous)
if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
return false;
return ac.Request.Method == HttpMethod.Get;
};
protected virtual void EnsureCacheTimeQuery()
{
if (CacheTimeQuery == null) ResetCacheTimeQuery();
}
protected void ResetCacheTimeQuery()
{
CacheTimeQuery = new ShortTime( ServerTimeSpan, ClientTimeSpan );
}
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))
{
var negotiatedResult = negotiator.Negotiate(returnType, actionContext.Request, config.Formatters);
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.Contains(responseMediaType)))
{
return DefaultMediaType;
}
}
}
return responseMediaType;
}
private 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);
_responseMediaType = GetExpectedMediaType(config, actionContext);
var cachekey = cacheKeyGenerator.MakeCacheKey(actionContext, _responseMediaType, ExcludeQueryStringFromCacheKey);
if (!_webApiCache.Contains(cachekey)) return;
var responseHeaders = _webApiCache.Get(cachekey + Constants.Headers) as string;
if (actionContext.Request.Headers.IfNoneMatch != null)
{
var etag = _webApiCache.Get(cachekey + Constants.EtagKey) as string;
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);
if (responseHeaders != null) AddCachedHeaders(quickResponse, responseHeaders);
ApplyCacheHeaders(quickResponse, time);
actionContext.Response = quickResponse;
return;
}
}
}
var val = _webApiCache.Get(cachekey) as byte[];
if (val == null) return;
var contenttype = _webApiCache.Get(cachekey + Constants.ContentTypeKey) as MediaTypeHeaderValue ?? new MediaTypeHeaderValue(cachekey.Split(new[] {':'},2)[1]);
actionContext.Response = actionContext.Request.CreateResponse();
actionContext.Response.Content = new ByteArrayContent(val);
actionContext.Response.Content.Headers.ContentType = contenttype;
var responseEtag = _webApiCache.Get(cachekey + Constants.EtagKey) as string;
if (responseEtag != null) SetEtag(actionContext.Response, responseEtag);
if (responseHeaders != null) AddCachedHeaders(actionContext.Response, responseHeaders);
var cacheTime = CacheTimeQuery.Execute(DateTime.Now);
ApplyCacheHeaders(actionContext.Response, cacheTime);
}
private async Task OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.ActionContext.Response == null || !actionExecutedContext.ActionContext.Response.IsSuccessStatusCode) return;
if (!_isCachingAllowed(actionExecutedContext.ActionContext, AnonymousOnly)) return;
var cacheTime = CacheTimeQuery.Execute(DateTime.Now);
if (cacheTime.AbsoluteExpiration > DateTime.Now)
{
var config = actionExecutedContext.Request.GetConfiguration().CacheOutputConfiguration();
var cacheKeyGenerator = config.GetCacheKeyGenerator(actionExecutedContext.Request, CacheKeyGenerator);
var cachekey = cacheKeyGenerator.MakeCacheKey(actionExecutedContext.ActionContext, _responseMediaType, ExcludeQueryStringFromCacheKey);
if (!string.IsNullOrWhiteSpace(cachekey) && !(_webApiCache.Contains(cachekey)))
{
SetEtag(actionExecutedContext.Response, Guid.NewGuid().ToString());
if (actionExecutedContext.Response.Content != null)
{
var baseKey = config.MakeBaseCachekey(actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName, actionExecutedContext.ActionContext.ActionDescriptor.ActionName);
var contentType = actionExecutedContext.Response.Content.Headers.ContentType;
string etag = actionExecutedContext.Response.Headers.ETag.Tag;
//ConfigureAwait false to avoid deadlocks
var content = await actionExecutedContext.Response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
actionExecutedContext.Response.Content.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);
if (!String.IsNullOrEmpty(HeadersToInclude))
{
string headersSerialized = JsonConvert.SerializeObject(actionExecutedContext.Response.Headers.Where(h => HeadersToInclude.Contains(h.Key)));
_webApiCache.Add(cachekey + Constants.Headers,
headersSerialized,
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,
MustRevalidate = MustRevalidate,
Private = Private
};
response.Headers.CacheControl = cachecontrol;
}
else if (NoCache)
{
response.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true };
response.Headers.Add("Pragma", "no-cache");
}
}
private static void SetEtag(HttpResponseMessage message, string etag)
{
if (etag != null)
{
var eTag = new EntityTagHeaderValue(@"""" + etag.Replace("\"", string.Empty) + @"""");
message.Headers.ETag = eTag;
}
}
protected virtual void AddCachedHeaders(HttpResponseMessage response, string headers)
{
var headersDeserialized = JsonConvert.DeserializeObject<IEnumerable<KeyValuePair<string, IEnumerable<string>>>>(headers);
foreach (var header in headersDeserialized)
{
foreach (var headerValue in header.Value)
{
response.Headers.Add(header.Key, headerValue);
}
}
}
Task<HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
if (actionContext == null)
{
throw new ArgumentNullException("actionContext");
}
if (continuation == null)
{
throw new ArgumentNullException("continuation");
}
OnActionExecuting(actionContext);
if (actionContext.Response != null)
{
return Task.FromResult(actionContext.Response);
}
return CallOnActionExecutedAsync(actionContext, cancellationToken, continuation);
}
private async Task<HttpResponseMessage> CallOnActionExecutedAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage response = null;
Exception exception = null;
try
{
response = await continuation();
}
catch (Exception e)
{
exception = e;
}
try
{
var executedContext = new HttpActionExecutedContext(actionContext, exception) { Response = response };
await OnActionExecuted(executedContext);
if (executedContext.Response != null)
{
return executedContext.Response;
}
if (executedContext.Exception != null)
{
ExceptionDispatchInfo.Capture(executedContext.Exception).Throw();
}
}
catch (Exception e)
{
actionContext.Response = null;
ExceptionDispatchInfo.Capture(e).Throw();
}
throw new InvalidOperationException(GetType().Name);
}
}
}