OutputCacheModule.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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.IO;
  32. using System.Text;
  33. using System.Web;
  34. using System.Web.UI;
  35. using System.Web.Util;
  36. using System.Web.Compilation;
  37. #if NET_2_0
  38. using System.Collections.Generic;
  39. #endif
  40. namespace System.Web.Caching {
  41. internal sealed class OutputCacheModule : IHttpModule
  42. {
  43. CacheItemRemovedCallback response_removed;
  44. #if NET_2_0
  45. static object keysCacheLock = new object ();
  46. Dictionary <string, string> keysCache;
  47. Dictionary <string, string> entriesToInvalidate;
  48. #endif
  49. public OutputCacheModule ()
  50. {
  51. }
  52. public void Dispose ()
  53. {
  54. }
  55. public void Init (HttpApplication context)
  56. {
  57. context.ResolveRequestCache += new EventHandler(OnResolveRequestCache);
  58. context.UpdateRequestCache += new EventHandler(OnUpdateRequestCache);
  59. response_removed = new CacheItemRemovedCallback (OnRawResponseRemoved);
  60. }
  61. #if NET_2_0
  62. void OnBuildManagerRemoveEntry (BuildManagerRemoveEntryEventArgs args)
  63. {
  64. string entry = args.EntryName;
  65. HttpContext context = args.Context;
  66. string cacheValue;
  67. lock (keysCacheLock) {
  68. if (!keysCache.TryGetValue (entry, out cacheValue))
  69. return;
  70. keysCache.Remove (entry);
  71. if (context == null) {
  72. if (entriesToInvalidate == null) {
  73. entriesToInvalidate = new Dictionary <string, string> (StringComparer.Ordinal);
  74. entriesToInvalidate.Add (entry, cacheValue);
  75. return;
  76. } else if (!entriesToInvalidate.ContainsKey (entry)) {
  77. entriesToInvalidate.Add (entry, cacheValue);
  78. return;
  79. }
  80. }
  81. }
  82. context.Cache.Remove (entry);
  83. if (!String.IsNullOrEmpty (cacheValue))
  84. context.InternalCache.Remove (cacheValue);
  85. }
  86. #endif
  87. void OnResolveRequestCache (object o, EventArgs args)
  88. {
  89. HttpApplication app = (HttpApplication) o;
  90. HttpContext context = app.Context;
  91. string vary_key = context.Request.FilePath;
  92. CachedVaryBy varyby = context.Cache [vary_key] as CachedVaryBy;
  93. string key;
  94. CachedRawResponse c;
  95. if (varyby == null)
  96. return;
  97. key = varyby.CreateKey (vary_key, context);
  98. c = context.InternalCache [key] as CachedRawResponse;
  99. if (c == null)
  100. return;
  101. #if NET_2_0
  102. lock (keysCacheLock) {
  103. string invValue;
  104. if (entriesToInvalidate != null && entriesToInvalidate.TryGetValue (vary_key, out invValue) && String.Compare (invValue, key, StringComparison.Ordinal) == 0) {
  105. context.Cache.Remove (vary_key);
  106. context.InternalCache.Remove (key);
  107. entriesToInvalidate.Remove (vary_key);
  108. return;
  109. }
  110. }
  111. #endif
  112. ArrayList callbacks = c.Policy.ValidationCallbacks;
  113. if (callbacks != null && callbacks.Count > 0) {
  114. bool isValid = true;
  115. bool isIgnored = false;
  116. foreach (Pair p in callbacks) {
  117. HttpCacheValidateHandler validate = (HttpCacheValidateHandler)p.First;
  118. object data = p.Second;
  119. HttpValidationStatus status = HttpValidationStatus.Valid;
  120. try {
  121. validate (context, data, ref status);
  122. } catch {
  123. // MS.NET hides the exception
  124. isValid = false;
  125. break;
  126. }
  127. if (status == HttpValidationStatus.Invalid) {
  128. isValid = false;
  129. break;
  130. } else if (status == HttpValidationStatus.IgnoreThisRequest) {
  131. isIgnored = true;
  132. }
  133. }
  134. if (!isValid) {
  135. OnRawResponseRemoved (key, c, CacheItemRemovedReason.Removed);
  136. return;
  137. } else if (isIgnored) {
  138. return;
  139. }
  140. }
  141. HttpResponse response = context.Response;
  142. response.ClearContent ();
  143. IList cachedData = c.GetData ();
  144. if (cachedData != null) {
  145. Encoding outEnc = WebEncoding.ResponseEncoding;
  146. foreach (CachedRawResponse.DataItem d in cachedData) {
  147. if (d.Length > 0) {
  148. response.BinaryWrite (d.Buffer, 0, (int)d.Length);
  149. continue;
  150. }
  151. #if NET_2_0
  152. if (d.Callback == null)
  153. continue;
  154. string s = d.Callback (context);
  155. if (s == null || s.Length == 0)
  156. continue;
  157. byte[] bytes = outEnc.GetBytes (s);
  158. response.BinaryWrite (bytes, 0, bytes.Length);
  159. #endif
  160. }
  161. }
  162. response.ClearHeaders ();
  163. response.SetCachedHeaders (c.Headers);
  164. response.StatusCode = c.StatusCode;
  165. response.StatusDescription = c.StatusDescription;
  166. app.CompleteRequest ();
  167. }
  168. void OnUpdateRequestCache (object o, EventArgs args)
  169. {
  170. HttpApplication app = (HttpApplication) o;
  171. HttpContext context = app.Context;
  172. if (context.Response.IsCached && context.Response.StatusCode == 200 &&
  173. !context.Trace.IsEnabled)
  174. DoCacheInsert (context);
  175. }
  176. void DoCacheInsert (HttpContext context)
  177. {
  178. string vary_key = context.Request.FilePath;
  179. string key;
  180. CachedVaryBy varyby = context.Cache [vary_key] as CachedVaryBy;
  181. CachedRawResponse prev = null;
  182. bool lookup = true;
  183. #if NET_2_0
  184. string cacheKey = null, cacheValue = null;
  185. #endif
  186. if (varyby == null) {
  187. string path = context.Request.MapPath (vary_key);
  188. string [] files = new string [] { path };
  189. string [] keys = new string [0];
  190. varyby = new CachedVaryBy (context.Response.Cache, vary_key);
  191. context.Cache.Insert (vary_key, varyby,
  192. new CacheDependency (files, keys),
  193. Cache.NoAbsoluteExpiration,
  194. Cache.NoSlidingExpiration,
  195. CacheItemPriority.Normal, null);
  196. lookup = false;
  197. #if NET_2_0
  198. cacheKey = vary_key;
  199. #endif
  200. }
  201. key = varyby.CreateKey (vary_key, context);
  202. if (lookup)
  203. prev = context.InternalCache [key] as CachedRawResponse;
  204. if (prev == null) {
  205. CachedRawResponse c = context.Response.GetCachedResponse ();
  206. if (c != null) {
  207. string [] files = new string [] { };
  208. string [] keys = new string [] { vary_key };
  209. bool sliding = context.Response.Cache.Sliding;
  210. context.InternalCache.Insert (key, c, new CacheDependency (files, keys),
  211. (sliding ? Cache.NoAbsoluteExpiration :
  212. context.Response.Cache.Expires),
  213. (sliding ? TimeSpan.FromSeconds (
  214. context.Response.Cache.Duration) :
  215. Cache.NoSlidingExpiration),
  216. CacheItemPriority.Normal, response_removed);
  217. c.VaryBy = varyby;
  218. varyby.ItemList.Add (key);
  219. #if NET_2_0
  220. cacheValue = key;
  221. #endif
  222. }
  223. }
  224. #if NET_2_0
  225. if (cacheKey != null) {
  226. lock (keysCacheLock) {
  227. if (keysCache == null) {
  228. BuildManager.RemoveEntry += new BuildManagerRemoveEntryEventHandler (OnBuildManagerRemoveEntry);
  229. keysCache = new Dictionary <string, string> (StringComparer.Ordinal);
  230. keysCache.Add (cacheKey, cacheValue);
  231. } else if (!keysCache.ContainsKey (cacheKey))
  232. keysCache.Add (cacheKey, cacheValue);
  233. }
  234. }
  235. #endif
  236. }
  237. static void OnRawResponseRemoved (string key, object value, CacheItemRemovedReason reason)
  238. {
  239. CachedRawResponse c = (CachedRawResponse) value;
  240. c.VaryBy.ItemList.Remove (key);
  241. if (c.VaryBy.ItemList.Count != 0)
  242. return;
  243. HttpRuntime.Cache.Remove (c.VaryBy.Key);
  244. }
  245. }
  246. }