public override void OnResultExecuted(ResultExecutedContext filterContext) { if (_originalWriter != null) // Must complete the caching // new request to cache - add it to the cache { HtmlTextWriter cacheWriter = (HtmlTextWriter)_switchWriterMethod.Invoke(HttpContext.Current.Response, new object[] { _originalWriter }); string textWritten = ((StringWriter)cacheWriter.InnerWriter).ToString(); textWritten = CreateDonutHoles(textWritten); CacheContainer container = new CacheContainer(textWritten, filterContext.HttpContext.Response); filterContext.HttpContext.Cache.Add(_cacheKey, container, null, DateTime.Now.AddSeconds(_cacheDuration), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); filterContext.HttpContext.Response.Write(ReplaceDonutHoles(textWritten)); var hardReload = filterContext.RequestContext.HttpContext.Request.Headers["Cache-Control"] == "no-cache"; filterContext.HttpContext.Response.Write("<!-- cache prep: " + _startTime.FmtMillisecondsElapsed() + " " + (hardReload ? "Hard Reload" : "") + " -->"); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { _originalWriter = null; if (_cacheDuration == 0) { return; } _startTime = DateTime.Now; _cacheKey = ComputeCacheKey(filterContext); CacheContainer cachedOutput = (CacheContainer)filterContext.HttpContext.Cache[_cacheKey]; var hardReload = filterContext.RequestContext.HttpContext.Request.Headers["Cache-Control"] == "no-cache"; if (cachedOutput != null && !hardReload) { // cache hit foreach (string header in cachedOutput.Headers) { // AF20141028 Don't include GZIP header if (header != "Content-Encoding") { filterContext.HttpContext.Response.Headers[header] = cachedOutput.Headers[header]; } } filterContext.HttpContext.Response.Status = cachedOutput.Status; filterContext.HttpContext.Response.StatusCode = cachedOutput.StatusCode; filterContext.HttpContext.Response.SubStatusCode = cachedOutput.SubStatusCode; filterContext.HttpContext.Response.ContentEncoding = cachedOutput.ContentEncoding; filterContext.HttpContext.Response.HeaderEncoding = cachedOutput.HeaderEncoding; filterContext.HttpContext.Response.Charset = cachedOutput.Charset; filterContext.HttpContext.Response.ContentType = cachedOutput.ContentType; filterContext.Result = new ContentResult { Content = ReplaceDonutHoles(cachedOutput.Output) + "<!-- cache hit: " + _startTime.FmtMillisecondsElapsed() + " -->" }; } else { // new request to cache StringWriter stringWriter = new StringWriterWithEncoding(filterContext.HttpContext.Response.ContentEncoding); HtmlTextWriter newWriter = new HtmlTextWriter(stringWriter); _originalWriter = (TextWriter)_switchWriterMethod.Invoke(HttpContext.Current.Response, new object[] { newWriter }); } }