Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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