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.0KB

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