OutputCacheModule.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. //
  2. // System.Web.Caching.OutputCacheModule
  3. //
  4. // Authors:
  5. // Jackson Harper ([email protected])
  6. // Marek Habersack <[email protected]>
  7. //
  8. // (C) 2003-2009 Novell, Inc (http://www.novell.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.IO;
  33. using System.Text;
  34. using System.Web;
  35. using System.Web.UI;
  36. using System.Web.Util;
  37. using System.Web.Compilation;
  38. namespace System.Web.Caching
  39. {
  40. sealed class OutputCacheModule : IHttpModule
  41. {
  42. CacheItemRemovedCallback response_removed;
  43. static object keysCacheLock = new object ();
  44. Dictionary <string, string> keysCache;
  45. Dictionary <string, string> entriesToInvalidate;
  46. public OutputCacheModule ()
  47. {
  48. }
  49. public void Dispose ()
  50. {
  51. }
  52. public void Init (HttpApplication context)
  53. {
  54. context.ResolveRequestCache += new EventHandler(OnResolveRequestCache);
  55. context.UpdateRequestCache += new EventHandler(OnUpdateRequestCache);
  56. response_removed = new CacheItemRemovedCallback (OnRawResponseRemoved);
  57. }
  58. void OnBuildManagerRemoveEntry (BuildManagerRemoveEntryEventArgs args)
  59. {
  60. string entry = args.EntryName;
  61. HttpContext context = args.Context;
  62. string cacheValue;
  63. lock (keysCacheLock) {
  64. if (!keysCache.TryGetValue (entry, out cacheValue))
  65. return;
  66. keysCache.Remove (entry);
  67. if (context == null) {
  68. if (entriesToInvalidate == null) {
  69. entriesToInvalidate = new Dictionary <string, string> (StringComparer.Ordinal);
  70. entriesToInvalidate.Add (entry, cacheValue);
  71. return;
  72. } else if (!entriesToInvalidate.ContainsKey (entry)) {
  73. entriesToInvalidate.Add (entry, cacheValue);
  74. return;
  75. }
  76. }
  77. }
  78. context.Cache.Remove (entry);
  79. if (!String.IsNullOrEmpty (cacheValue))
  80. context.InternalCache.Remove (cacheValue);
  81. }
  82. void OnResolveRequestCache (object o, EventArgs args)
  83. {
  84. HttpApplication app = (HttpApplication) o;
  85. HttpContext context = app.Context;
  86. string vary_key = context.Request.FilePath;
  87. CachedVaryBy varyby = context.Cache [vary_key] as CachedVaryBy;
  88. string key;
  89. CachedRawResponse c;
  90. if (varyby == null)
  91. return;
  92. key = varyby.CreateKey (vary_key, context);
  93. c = context.InternalCache [key] as CachedRawResponse;
  94. if (c == null)
  95. return;
  96. lock (keysCacheLock) {
  97. string invValue;
  98. if (entriesToInvalidate != null && entriesToInvalidate.TryGetValue (vary_key, out invValue) && String.Compare (invValue, key, StringComparison.Ordinal) == 0) {
  99. context.Cache.Remove (vary_key);
  100. context.InternalCache.Remove (key);
  101. entriesToInvalidate.Remove (vary_key);
  102. return;
  103. }
  104. }
  105. ArrayList callbacks = c.Policy.ValidationCallbacks;
  106. if (callbacks != null && callbacks.Count > 0) {
  107. bool isValid = true;
  108. bool isIgnored = false;
  109. foreach (Pair p in callbacks) {
  110. HttpCacheValidateHandler validate = (HttpCacheValidateHandler)p.First;
  111. object data = p.Second;
  112. HttpValidationStatus status = HttpValidationStatus.Valid;
  113. try {
  114. validate (context, data, ref status);
  115. } catch {
  116. // MS.NET hides the exception
  117. isValid = false;
  118. break;
  119. }
  120. if (status == HttpValidationStatus.Invalid) {
  121. isValid = false;
  122. break;
  123. } else if (status == HttpValidationStatus.IgnoreThisRequest) {
  124. isIgnored = true;
  125. }
  126. }
  127. if (!isValid) {
  128. OnRawResponseRemoved (key, c, CacheItemRemovedReason.Removed);
  129. return;
  130. } else if (isIgnored) {
  131. return;
  132. }
  133. }
  134. HttpResponse response = context.Response;
  135. response.ClearContent ();
  136. IList cachedData = c.GetData ();
  137. if (cachedData != null) {
  138. Encoding outEnc = WebEncoding.ResponseEncoding;
  139. foreach (CachedRawResponse.DataItem d in cachedData) {
  140. if (d.Length > 0) {
  141. response.BinaryWrite (d.Buffer, 0, (int)d.Length);
  142. continue;
  143. }
  144. if (d.Callback == null)
  145. continue;
  146. string s = d.Callback (context);
  147. if (s == null || s.Length == 0)
  148. continue;
  149. byte[] bytes = outEnc.GetBytes (s);
  150. response.BinaryWrite (bytes, 0, bytes.Length);
  151. }
  152. }
  153. response.ClearHeaders ();
  154. response.SetCachedHeaders (c.Headers);
  155. response.StatusCode = c.StatusCode;
  156. response.StatusDescription = c.StatusDescription;
  157. app.CompleteRequest ();
  158. }
  159. void OnUpdateRequestCache (object o, EventArgs args)
  160. {
  161. HttpApplication app = (HttpApplication) o;
  162. HttpContext context = app.Context;
  163. if (context.Response.IsCached && context.Response.StatusCode == 200 &&
  164. !context.Trace.IsEnabled)
  165. DoCacheInsert (context);
  166. }
  167. void DoCacheInsert (HttpContext context)
  168. {
  169. string vary_key = context.Request.FilePath;
  170. string key;
  171. CachedVaryBy varyby = context.Cache [vary_key] as CachedVaryBy;
  172. CachedRawResponse prev = null;
  173. bool lookup = true;
  174. string cacheKey = null, cacheValue = null;
  175. if (varyby == null) {
  176. string path = context.Request.MapPath (vary_key);
  177. string [] files = new string [] { path };
  178. string [] keys = new string [0];
  179. varyby = new CachedVaryBy (context.Response.Cache, vary_key);
  180. context.Cache.Insert (vary_key, varyby,
  181. new CacheDependency (files, keys),
  182. Cache.NoAbsoluteExpiration,
  183. Cache.NoSlidingExpiration,
  184. CacheItemPriority.Normal, null);
  185. lookup = false;
  186. cacheKey = vary_key;
  187. }
  188. key = varyby.CreateKey (vary_key, context);
  189. if (lookup)
  190. prev = context.InternalCache [key] as CachedRawResponse;
  191. if (prev == null) {
  192. CachedRawResponse c = context.Response.GetCachedResponse ();
  193. if (c != null) {
  194. string [] files = new string [] { };
  195. string [] keys = new string [] { vary_key };
  196. bool sliding = context.Response.Cache.Sliding;
  197. context.InternalCache.Insert (key, c, new CacheDependency (files, keys),
  198. (sliding ? Cache.NoAbsoluteExpiration :
  199. context.Response.Cache.Expires),
  200. (sliding ? TimeSpan.FromSeconds (
  201. context.Response.Cache.Duration) :
  202. Cache.NoSlidingExpiration),
  203. CacheItemPriority.Normal, response_removed);
  204. c.VaryBy = varyby;
  205. varyby.ItemList.Add (key);
  206. cacheValue = key;
  207. }
  208. }
  209. if (cacheKey != null) {
  210. lock (keysCacheLock) {
  211. if (keysCache == null) {
  212. BuildManager.RemoveEntry += new BuildManagerRemoveEntryEventHandler (OnBuildManagerRemoveEntry);
  213. keysCache = new Dictionary <string, string> (StringComparer.Ordinal);
  214. keysCache.Add (cacheKey, cacheValue);
  215. } else if (!keysCache.ContainsKey (cacheKey))
  216. keysCache.Add (cacheKey, cacheValue);
  217. }
  218. }
  219. }
  220. static void OnRawResponseRemoved (string key, object value, CacheItemRemovedReason reason)
  221. {
  222. CachedRawResponse c = (CachedRawResponse) value;
  223. c.VaryBy.ItemList.Remove (key);
  224. if (c.VaryBy.ItemList.Count != 0)
  225. return;
  226. HttpRuntime.Cache.Remove (c.VaryBy.Key);
  227. }
  228. }
  229. }