You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CacheControlAttribute.cs 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Net.Http;
  5. using System.Net.Http.Formatting;
  6. using System.Net.Http.Headers;
  7. using System.Runtime.ExceptionServices;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Web.Http;
  12. using System.Web.Http.Controllers;
  13. using System.Web.Http.Filters;
  14. using iiie.CacheControl.Business.HttpExtensions;
  15. using iiie.CacheControl.Business.OutputCache;
  16. using iiie.CacheControl.DBO;
  17. namespace iiie.CacheControl.Attributes
  18. {
  19. [AttributeUsage(AttributeTargets.Method)]
  20. public abstract class CacheControlAttribute : FilterAttribute, IActionFilter
  21. {
  22. protected static MediaTypeHeaderValue DefaultMediaType = new MediaTypeHeaderValue("application/json");
  23. /// <summary>
  24. /// Indicates if the client can reuse cached data without asking origin server
  25. /// </summary>
  26. protected bool MustRevalidate { get; set; }
  27. /// <summary>
  28. /// Data used by OutputCache
  29. /// </summary>
  30. protected object CacheOutputData { get; set; }
  31. /// <summary>
  32. /// Indicates if the query string must be used to control cache
  33. /// </summary>
  34. protected bool ExcludeQueryStringFromCacheKey { get; set; }
  35. /// <summary>
  36. /// Define the cache type used to store cache
  37. /// </summary>
  38. protected OutputCacheType CacheType { get; set; }
  39. protected Type CacheKeyGenerator { get; set; }
  40. private MediaTypeHeaderValue _responseMediaType;
  41. private IOutputCache _webCache;
  42. protected void EnsureCache(HttpConfiguration config, HttpRequestMessage req)
  43. {
  44. _webCache = config.CacheOutputConfiguration(CacheType).GetCacheOutputProvider(req, CacheOutputData);
  45. }
  46. protected abstract bool IsValid(CacheDbo data);
  47. protected virtual CacheDbo CreateCacheUser()
  48. {
  49. return new CacheDbo();
  50. }
  51. protected virtual MediaTypeHeaderValue GetExpectedMediaType(HttpConfiguration config, HttpActionContext actionContext)
  52. {
  53. MediaTypeHeaderValue responseMediaType = null;
  54. var negotiator = config.Services.GetService(typeof(IContentNegotiator)) as IContentNegotiator;
  55. var returnType = actionContext.ActionDescriptor.ReturnType;
  56. if (negotiator != null && returnType != typeof(HttpResponseMessage))
  57. {
  58. var negotiatedResult = negotiator.Negotiate(returnType, actionContext.Request, config.Formatters);
  59. responseMediaType = negotiatedResult.MediaType;
  60. responseMediaType.CharSet = Encoding.UTF8.HeaderName;
  61. }
  62. else
  63. {
  64. if (actionContext.Request.Headers.Accept != null)
  65. {
  66. responseMediaType = actionContext.Request.Headers.Accept.FirstOrDefault();
  67. if (responseMediaType == null ||
  68. !config.Formatters.Any(x => x.SupportedMediaTypes.Contains(responseMediaType)))
  69. {
  70. DefaultMediaType.CharSet = Encoding.UTF8.HeaderName;
  71. return DefaultMediaType;
  72. }
  73. }
  74. }
  75. return responseMediaType;
  76. }
  77. private void OnActionExecuting(HttpActionContext actionContext)
  78. {
  79. if (actionContext == null) throw new ArgumentNullException("actionContext");
  80. var config = actionContext.Request.GetConfiguration();
  81. EnsureCache(config, actionContext.Request);
  82. var cacheKeyGenerator = config.CacheOutputConfiguration(CacheType).GetCacheKeyGenerator(actionContext.Request, CacheKeyGenerator);
  83. _responseMediaType = GetExpectedMediaType(config, actionContext);
  84. var cachekey = cacheKeyGenerator.MakeCacheKey(actionContext, _responseMediaType, CacheType, ExcludeQueryStringFromCacheKey);
  85. var data = _webCache.Get<CacheDbo>(cachekey);
  86. if (data == null)
  87. return;
  88. if (!IsValid(data))
  89. {
  90. _webCache.Remove(cachekey);
  91. return;
  92. }
  93. if (actionContext.Request.Headers.IfNoneMatch != null)
  94. {
  95. if (data.ETag != null)
  96. {
  97. if (actionContext.Request.Headers.IfNoneMatch.Any(x => x.Tag == data.ETag))
  98. {
  99. var quickResponse = actionContext.Request.CreateResponse(HttpStatusCode.NotModified);
  100. ApplyCacheHeaders(quickResponse);
  101. actionContext.Response = quickResponse;
  102. return;
  103. }
  104. }
  105. }
  106. if (data.Content == null) return;
  107. actionContext.Response = actionContext.Request.CreateResponse();
  108. actionContext.Response.Content = new ByteArrayContent(data.Content);
  109. actionContext.Response.Content.Headers.ContentType = new MediaTypeHeaderValue(data.ContentType);
  110. if (data.ETag != null) SetEtag(actionContext.Response, data.ETag);
  111. ApplyCacheHeaders(actionContext.Response);
  112. }
  113. private async Task OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
  114. {
  115. if (actionExecutedContext.ActionContext.Response == null || !actionExecutedContext.ActionContext.Response.IsSuccessStatusCode) return;
  116. var config = actionExecutedContext.Request.GetConfiguration().CacheOutputConfiguration(CacheType);
  117. var cacheKeyGenerator = config.GetCacheKeyGenerator(actionExecutedContext.Request, CacheKeyGenerator);
  118. var cachekey = cacheKeyGenerator.MakeCacheKey(actionExecutedContext.ActionContext, _responseMediaType, CacheType, ExcludeQueryStringFromCacheKey);
  119. if (!string.IsNullOrWhiteSpace(cachekey) && !(_webCache.Contains(cachekey)))
  120. {
  121. SetEtag(actionExecutedContext.Response, Guid.NewGuid().ToString());
  122. if (actionExecutedContext.Response.Content != null)
  123. {
  124. var data = CreateCacheUser();
  125. data.Content = await actionExecutedContext.Response.Content.ReadAsByteArrayAsync();
  126. data.ContentType = actionExecutedContext.Response.Content.Headers.ContentType.MediaType;
  127. data.ETag = actionExecutedContext.Response.Headers.ETag.Tag;
  128. data.Date = DateTime.Now;
  129. _webCache.Add(cachekey, data);
  130. }
  131. }
  132. ApplyCacheHeaders(actionExecutedContext.ActionContext.Response);
  133. }
  134. private void ApplyCacheHeaders(HttpResponseMessage response)
  135. {
  136. if (MustRevalidate)
  137. {
  138. response.Headers.CacheControl = new CacheControlHeaderValue
  139. {
  140. MustRevalidate = MustRevalidate
  141. };
  142. }
  143. }
  144. private static void SetEtag(HttpResponseMessage message, string etag)
  145. {
  146. if (etag != null)
  147. {
  148. message.Headers.ETag = new EntityTagHeaderValue(@"""" + etag.Replace("\"", string.Empty) + @"""");
  149. }
  150. }
  151. Task<HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
  152. {
  153. if (actionContext == null)
  154. {
  155. throw new ArgumentNullException("actionContext");
  156. }
  157. if (continuation == null)
  158. {
  159. throw new ArgumentNullException("continuation");
  160. }
  161. OnActionExecuting(actionContext);
  162. if (actionContext.Response != null)
  163. {
  164. return Task.FromResult(actionContext.Response);
  165. }
  166. return CallOnActionExecutedAsync(actionContext, cancellationToken, continuation);
  167. }
  168. private async Task<HttpResponseMessage> CallOnActionExecutedAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
  169. {
  170. cancellationToken.ThrowIfCancellationRequested();
  171. HttpResponseMessage response = null;
  172. Exception exception = null;
  173. try
  174. {
  175. response = await continuation();
  176. }
  177. catch (Exception e)
  178. {
  179. exception = e;
  180. }
  181. try
  182. {
  183. var executedContext = new HttpActionExecutedContext(actionContext, exception) { Response = response };
  184. await OnActionExecuted(executedContext);
  185. if (executedContext.Response != null)
  186. {
  187. return executedContext.Response;
  188. }
  189. if (executedContext.Exception != null)
  190. {
  191. ExceptionDispatchInfo.Capture(executedContext.Exception).Throw();
  192. }
  193. }
  194. catch (Exception e)
  195. {
  196. actionContext.Response = null;
  197. ExceptionDispatchInfo.Capture(e).Throw();
  198. }
  199. throw new InvalidOperationException(GetType().Name);
  200. }
  201. }
  202. }