Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

CacheControlAttribute.cs 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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(cachekey) as CacheDbo;
  82. if (data == null) return;
  83. if (!IsValid(data))
  84. {
  85. _webCache.Remove(cachekey);
  86. return;
  87. }
  88. if (actionContext.Request.Headers.IfNoneMatch != null)
  89. {
  90. if (data.ETag != null)
  91. {
  92. if (actionContext.Request.Headers.IfNoneMatch.Any(x => x.Tag == data.ETag))
  93. {
  94. var quickResponse = actionContext.Request.CreateResponse(HttpStatusCode.NotModified);
  95. ApplyCacheHeaders(quickResponse);
  96. actionContext.Response = quickResponse;
  97. return;
  98. }
  99. }
  100. }
  101. if (data.Content == null) return;
  102. actionContext.Response = actionContext.Request.CreateResponse();
  103. actionContext.Response.Content = new ByteArrayContent(data.Content);
  104. actionContext.Response.Content.Headers.ContentType = new MediaTypeHeaderValue(data.ContentType);
  105. if (data.ETag != null) SetEtag(actionContext.Response, data.ETag);
  106. ApplyCacheHeaders(actionContext.Response);
  107. }
  108. private async Task OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
  109. {
  110. if (actionExecutedContext.ActionContext.Response == null || !actionExecutedContext.ActionContext.Response.IsSuccessStatusCode) return;
  111. var config = actionExecutedContext.Request.GetConfiguration().CacheOutputConfiguration(CacheType);
  112. var cacheKeyGenerator = config.GetCacheKeyGenerator(actionExecutedContext.Request, CacheKeyGenerator);
  113. var cachekey = cacheKeyGenerator.MakeCacheKey(actionExecutedContext.ActionContext, _responseMediaType, CacheType, ExcludeQueryStringFromCacheKey);
  114. if (!string.IsNullOrWhiteSpace(cachekey) && !(_webCache.Contains(cachekey)))
  115. {
  116. SetEtag(actionExecutedContext.Response, Guid.NewGuid().ToString());
  117. if (actionExecutedContext.Response.Content != null)
  118. {
  119. var data = CreateCacheUser();
  120. data.Content = await actionExecutedContext.Response.Content.ReadAsByteArrayAsync();
  121. data.ContentType = actionExecutedContext.Response.Content.Headers.ContentType.MediaType;
  122. data.ETag = actionExecutedContext.Response.Headers.ETag.Tag;
  123. data.Date = DateTime.Now;
  124. _webCache.Add(cachekey, data);
  125. }
  126. }
  127. ApplyCacheHeaders(actionExecutedContext.ActionContext.Response);
  128. }
  129. private void ApplyCacheHeaders(HttpResponseMessage response)
  130. {
  131. if (MustRevalidate)
  132. {
  133. response.Headers.CacheControl = new CacheControlHeaderValue
  134. {
  135. MustRevalidate = MustRevalidate
  136. };
  137. }
  138. }
  139. private static void SetEtag(HttpResponseMessage message, string etag)
  140. {
  141. if (etag != null)
  142. {
  143. message.Headers.ETag = new EntityTagHeaderValue(@"""" + etag.Replace("\"", string.Empty) + @"""");
  144. }
  145. }
  146. Task<HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
  147. {
  148. if (actionContext == null)
  149. {
  150. throw new ArgumentNullException("actionContext");
  151. }
  152. if (continuation == null)
  153. {
  154. throw new ArgumentNullException("continuation");
  155. }
  156. OnActionExecuting(actionContext);
  157. if (actionContext.Response != null)
  158. {
  159. return Task.FromResult(actionContext.Response);
  160. }
  161. return CallOnActionExecutedAsync(actionContext, cancellationToken, continuation);
  162. }
  163. private async Task<HttpResponseMessage> CallOnActionExecutedAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
  164. {
  165. cancellationToken.ThrowIfCancellationRequested();
  166. HttpResponseMessage response = null;
  167. Exception exception = null;
  168. try
  169. {
  170. response = await continuation();
  171. }
  172. catch (Exception e)
  173. {
  174. exception = e;
  175. }
  176. try
  177. {
  178. var executedContext = new HttpActionExecutedContext(actionContext, exception) { Response = response };
  179. await OnActionExecuted(executedContext);
  180. if (executedContext.Response != null)
  181. {
  182. return executedContext.Response;
  183. }
  184. if (executedContext.Exception != null)
  185. {
  186. ExceptionDispatchInfo.Capture(executedContext.Exception).Throw();
  187. }
  188. }
  189. catch (Exception e)
  190. {
  191. actionContext.Response = null;
  192. ExceptionDispatchInfo.Capture(e).Throw();
  193. }
  194. throw new InvalidOperationException(GetType().Name);
  195. }
  196. }
  197. }