/// <summary> /// This will make the browser and server keep the output /// in its cache and thereby improve performance. /// </summary> /// <param name="context"> /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides /// references to the intrinsic server objects /// </param> /// <param name="responseType"> /// The HTTP MIME type to send. /// </param> /// <param name="dependencyPaths"> /// The dependency path for the cache dependency. /// </param> private void SetHeaders(HttpContext context, string responseType, IEnumerable <string> dependencyPaths) { if (this.imageCache != null) { HttpResponse response = context.Response; if (response.Headers["ImageProcessedBy"] == null) { response.AddHeader("ImageProcessedBy", "ImageProcessor.Web/" + AssemblyVersion); } HttpCachePolicy cache = response.Cache; cache.SetCacheability(HttpCacheability.Public); cache.VaryByHeaders["Accept-Encoding"] = true; if (!string.IsNullOrWhiteSpace(responseType)) { response.ContentType = responseType; } if (dependencyPaths != null) { context.Response.AddFileDependencies(dependencyPaths.ToArray()); cache.SetLastModifiedFromFileDependencies(); } int maxDays = this.imageCache.MaxDays; cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays)); cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0)); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); this.imageCache = null; } }
/// <summary> /// This will make the browser and server keep the output /// in its cache and thereby improve performance. /// </summary> /// <param name="context"> /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides /// references to the intrinsic server objects /// </param> /// <param name="responseType"> /// The HTTP MIME type to send. /// </param> /// <param name="dependencyPaths"> /// The dependency path for the cache dependency. /// </param> private void SetHeaders(HttpContext context, string responseType, IEnumerable <string> dependencyPaths) { HttpResponse response = context.Response; response.ContentType = responseType; if (response.Headers["Image-Served-By"] == null) { response.AddHeader("Image-Served-By", "ImageProcessor.Web/" + AssemblyVersion); } HttpCachePolicy cache = response.Cache; cache.SetCacheability(HttpCacheability.Public); cache.VaryByHeaders["Accept-Encoding"] = true; context.Response.AddFileDependencies(dependencyPaths.ToArray()); cache.SetLastModifiedFromFileDependencies(); int maxDays = DiskCache.MaxFileCachedDuration; cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays)); cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0)); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); context.Items[CachedResponseTypeKey] = null; context.Items[CachedResponseFileDependency] = null; }
public void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; string physicalPath = request.PhysicalPath; if (File.Exists(physicalPath)) { string subfix = Path.GetExtension(physicalPath); bool isOutputCache = false; HttpResponse response = context.Response; if (".png".Equals(subfix, StringComparison.CurrentCultureIgnoreCase)) { isOutputCache = true; response.ContentType = "image/x-png"; } else if (".jpg".Equals(subfix, StringComparison.CurrentCultureIgnoreCase)) { isOutputCache = true; response.ContentType = "image/pjpeg"; } if (isOutputCache) { const int DAYS = 30; string ifModifiedSince = request.Headers["If-Modified-Since"]; if (!string.IsNullOrEmpty(ifModifiedSince) && TimeSpan.FromTicks(DateTime.Now.Ticks - DateTime.Parse(ifModifiedSince).Ticks).Days < DAYS) { response.StatusCode = (int)System.Net.HttpStatusCode.NotModified; response.StatusDescription = "Not Modified"; response.End(); return; } else { HttpCachePolicy cache = response.Cache; cache.SetLastModifiedFromFileDependencies(); cache.SetETagFromFileDependencies(); cache.SetCacheability(HttpCacheability.Public); cache.SetExpires(DateTime.Now.AddDays(DAYS)); TimeSpan timeSpan = TimeSpan.FromDays(DAYS); cache.SetMaxAge(timeSpan); cache.SetProxyMaxAge(timeSpan); cache.SetLastModified(context.Timestamp); cache.SetValidUntilExpires(true); cache.SetSlidingExpiration(true); } } response.WriteFile(physicalPath); response.End(); } }
/// <summary> /// 缓存 /// </summary> /// <param name="instance">HttpContext扩展</param> /// <param name="duration">时间差</param> public static void Cache(this HttpContext instance, TimeSpan duration) { instance.CheckOnNull("instance"); HttpCachePolicy cache = instance.Response.Cache; cache.SetCacheability(HttpCacheability.Public); cache.SetOmitVaryStar(true); cache.SetExpires(instance.Timestamp.Add(duration)); cache.SetMaxAge(duration); cache.SetValidUntilExpires(true); cache.SetLastModified(instance.Timestamp); cache.SetLastModifiedFromFileDependencies(); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); }
private void SetResponseCache(HttpContext context) { HttpCachePolicy cache = context.Response.Cache; cache.SetLastModified(DateTime.Now.ToUniversalTime().AddSeconds(-1.0)); cache.SetOmitVaryStar(true); cache.SetVaryByCustom("v"); cache.SetExpires(DateTime.UtcNow.AddDays(365.0)); cache.SetMaxAge(TimeSpan.FromDays(365.0)); cache.SetValidUntilExpires(true); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); cache.SetCacheability(HttpCacheability.Public); cache.SetLastModifiedFromFileDependencies(); }
public void ProcessRequest(HttpContext context) { string[] jsFiles = context.Request.QueryString["jsfiles"].Split(','); List <string> files = new List <string>(); StringBuilder response = new StringBuilder(); foreach (string jsFile in jsFiles) { if (!jsFile.EndsWith(".js", StringComparison.OrdinalIgnoreCase)) { //log custom exception context.Response.StatusCode = 403; return; } try { JavaScriptCompressor javaScriptCompressor = new JavaScriptCompressor(); string filePath = context.Server.MapPath(jsFile); string js = File.ReadAllText(filePath); string compressedJS = javaScriptCompressor.Compress(js); response.Append(compressedJS); } catch (Exception ex) { //log exception context.Response.StatusCode = 500; return; } } context.Response.Write(response.ToString()); string version = "1.0"; //your dynamic version number here context.Response.ContentType = "application/javascript"; context.Response.AddFileDependencies(files.ToArray()); HttpCachePolicy cache = context.Response.Cache; cache.SetCacheability(HttpCacheability.Public); cache.VaryByParams["jsfiles"] = true; cache.VaryByParams["version"] = true; cache.SetETag(version); cache.SetLastModifiedFromFileDependencies(); cache.SetMaxAge(TimeSpan.FromDays(14)); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); }
/// <summary> /// This will make the browser and server keep the output /// in its cache and thereby improve performance. /// </summary> /// <param name="context"> /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides /// references to the intrinsic server objects /// </param> /// <param name="responseType">The HTTP MIME type to send.</param> /// <param name="dependencyPaths">The dependency path for the cache dependency.</param> /// <param name="maxDays">The maximum number of days to store the image in the browser cache.</param> /// <param name="statusCode">An optional status code to send to the response.</param> public static void SetHeaders(HttpContext context, string responseType, string[] dependencyPaths, int maxDays, HttpStatusCode?statusCode = null) { HttpResponse response = context.Response; if (response.Headers["ImageProcessedBy"] == null) { response.AddHeader("ImageProcessedBy", $"ImageProcessor/{AssemblyVersion} - ImageProcessor.Web/{WebAssemblyVersion}"); } HttpCachePolicy cache = response.Cache; cache.SetCacheability(HttpCacheability.Public); cache.VaryByHeaders["Accept-Encoding"] = true; if (!string.IsNullOrWhiteSpace(responseType)) { response.ContentType = responseType; } if (dependencyPaths != null) { context.Response.AddFileDependencies(dependencyPaths.ToArray()); cache.SetLastModifiedFromFileDependencies(); } if (statusCode != null) { response.StatusCode = (int)statusCode; } cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays)); cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0)); if (ParseCacheBuster(context.Request.QueryString)) { cache.AppendCacheExtension("immutable"); } else { cache.SetRevalidation(HttpCacheRevalidation.AllCaches); } AddCorsRequestHeaders(context); }
/// <summary> /// 设置浏览器缓存 /// </summary> public void SetResponseCache() { HttpCachePolicy cache = HttpCurrentContext.Response.Cache; DateTime modifiedDate = new DateTime(AssemblyManager.GetAssemblyTime(typeof(ResourceManager).Assembly).Ticks).ToUniversalTime(); DateTime nowDate = DateTime.Now.ToUniversalTime().AddSeconds(-1); if (modifiedDate > nowDate) { modifiedDate = nowDate; } cache.SetLastModified(modifiedDate); cache.SetOmitVaryStar(true); cache.SetVaryByCustom("v"); cache.SetExpires(DateTime.UtcNow.AddDays(365)); cache.SetMaxAge(TimeSpan.FromDays(365)); cache.SetValidUntilExpires(true); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); cache.SetCacheability(HttpCacheability.Public); cache.SetLastModifiedFromFileDependencies(); }
void IHttpHandler.ProcessRequest(HttpContext context) { string theme = context.Request.QueryString["theme"]; string accent = context.Request.QueryString["accent"]; if (String.IsNullOrEmpty(theme) || String.IsNullOrEmpty(accent)) { throw new HttpException(400, "Bad Request"); } ApplicationServices services = new ApplicationServices(); string css = ApplicationServices.Current.CompileThemeStylesheet(String.Format("touch-theme.{0}.{1}.css", theme, accent)); context.Response.ContentType = "text/css"; HttpCachePolicy cache = context.Response.Cache; cache.SetCacheability(HttpCacheability.Public); cache.SetOmitVaryStar(true); cache.SetExpires(System.DateTime.Now.AddDays(365)); cache.SetValidUntilExpires(true); cache.SetLastModifiedFromFileDependencies(); ApplicationServices.CompressOutput(context, css); }
/// <summary> /// Sets the Last-Modified HTTP header based on the time stamps of the handler's file dependencies. /// </summary> public void SetLastModifiedFromFileDependencies() { policy.SetLastModifiedFromFileDependencies(); }
/// <summary> /// Outputs the combined script file requested by the HttpRequest to the HttpResponse /// </summary> /// <param name="context">HttpContext for the transaction</param> /// <returns>true if the script file was output</returns> public static bool OutputCombinedScriptFile(HttpContext context) { // Initialize bool output = false; HttpRequest request = context.Request; string hiddenFieldName; string combinedScripts; if (request.RequestType.ToUpper() == "GET") { hiddenFieldName = request.Params[HiddenFieldParamName]; combinedScripts = request.Params[CombinedScriptsParamName]; } else { #if NET45 hiddenFieldName = request.Form[HiddenFieldParamName]; combinedScripts = request.Form[CombinedScriptsParamName]; #else hiddenFieldName = request.Params[HiddenFieldParamName]; combinedScripts = request.Params[CombinedScriptsParamName]; #endif } if (!string.IsNullOrEmpty(hiddenFieldName) && !string.IsNullOrEmpty(combinedScripts)) { // This is a request for a combined script file HttpResponse response = context.Response; response.ContentType = "application/x-javascript"; // Set the same (~forever) caching rules that ScriptResource.axd uses HttpCachePolicy cache = response.Cache; cache.SetCacheability(HttpCacheability.Public); cache.VaryByParams[HiddenFieldParamName] = true; cache.VaryByParams[CombinedScriptsParamName] = true; cache.SetOmitVaryStar(true); cache.SetExpires(DateTime.Now.AddDays(365)); cache.SetValidUntilExpires(true); cache.SetLastModifiedFromFileDependencies(); // Get the stream to write the combined script to (using a compressed stream if requested) // Note that certain versions of IE6 have difficulty with compressed responses, so we // don't compress for those browsers (just like ASP.NET AJAX's ScriptResourceHandler) Stream outputStream = response.OutputStream; if (!request.Browser.IsBrowser("IE") || (6 < request.Browser.MajorVersion)) { foreach (string acceptEncoding in (request.Headers["Accept-Encoding"] ?? "").ToUpperInvariant().Split(',')) { if ("GZIP" == acceptEncoding) { // Browser wants GZIP; wrap the output stream with a GZipStream response.AddHeader("Content-encoding", "gzip"); outputStream = new GZipStream(outputStream, CompressionMode.Compress); break; } else if ("DEFLATE" == acceptEncoding) { // Browser wants Deflate; wrap the output stream with a DeflateStream response.AddHeader("Content-encoding", "deflate"); outputStream = new DeflateStream(outputStream, CompressionMode.Compress); break; } } } // Output the combined script using (StreamWriter outputWriter = new StreamWriter(outputStream)) { // Get the list of scripts to combine List <ScriptEntry> scriptEntries = DeserializeScriptEntries(HttpUtility.UrlDecode(combinedScripts), false); // Write the scripts WriteScripts(scriptEntries, outputWriter); // Write the ASP.NET AJAX script notification code outputWriter.WriteLine("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();"); // Write a handler to run on page load and update the hidden field tracking scripts loaded in the browser outputWriter.WriteLine(string.Format(CultureInfo.InvariantCulture, "(function() {{" + "var fn = function() {{" + "$get(\"{0}\").value += '{1}';" + "Sys.Application.remove_load(fn);" + "}};" + "Sys.Application.add_load(fn);" + "}})();", QuoteString(hiddenFieldName), SerializeScriptEntries(scriptEntries, true))); } output = true; } return(output); }
public override void SetLastModifiedFromFileDependencies() { _httpCachePolicy.SetLastModifiedFromFileDependencies(); }
public void Deny_Unrestricted() { HttpCachePolicy cache = response.Cache; Assert.IsNotNull(cache.VaryByHeaders, "VaryByHeaders"); Assert.IsNotNull(cache.VaryByParams, "VaryByParams"); cache.AddValidationCallback(new HttpCacheValidateHandler(Validate), null); cache.AppendCacheExtension("mono"); cache.SetCacheability(HttpCacheability.NoCache); cache.SetCacheability(HttpCacheability.NoCache, "mono"); cache.SetETag("etag"); try { cache.SetETagFromFileDependencies(); } catch (TypeInitializationException) { // 1.1 tries to initialize HttpRuntime } catch (InvalidOperationException) { // expected } cache.SetExpires(DateTime.MinValue); cache.SetLastModified(DateTime.Now); try { cache.SetLastModifiedFromFileDependencies(); } catch (InvalidOperationException) { // expected } catch (NotImplementedException) { // mono } cache.SetMaxAge(TimeSpan.FromTicks(1000)); try { cache.SetNoServerCaching(); } catch (NotImplementedException) { // mono } try { cache.SetNoStore(); } catch (NotImplementedException) { // mono } try { cache.SetNoTransforms(); } catch (NotImplementedException) { // mono } cache.SetProxyMaxAge(TimeSpan.FromTicks(2000)); cache.SetRevalidation(HttpCacheRevalidation.None); cache.SetSlidingExpiration(true); try { cache.SetValidUntilExpires(true); } catch (NotImplementedException) { // mono } cache.SetVaryByCustom("custom"); cache.SetAllowResponseInBrowserHistory(true); #if NET_2_0 try { cache.SetOmitVaryStar(false); } catch (NotImplementedException) { // mono } #endif }
/// <summary> /// This will make the browser and server keep the output /// in its cache and thereby improve performance. /// See http://en.wikipedia.org/wiki/HTTP_ETag /// </summary> /// <param name="path"> /// The combined path to the items. /// </param> /// <param name="context"> /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides /// references to the intrinsic server objects /// </param> /// <param name="responseType"> /// The HTTP MIME type to to send. /// </param> /// <param name="futureExpire"> /// Whether the response headers should be set to expire in the future. /// </param> /// <param name="fileMonitors"> /// The file Monitors. /// </param> protected void SetHeaders(string path, HttpContext context, ResponseType responseType, bool futureExpire, IList <string> fileMonitors) { // Generate a hash from the combined last write times of any monitors and // the path. StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(path); if (fileMonitors != null) { foreach (string fileMonitor in fileMonitors) { FileInfo fileInfo = new FileInfo(fileMonitor); stringBuilder.AppendFormat("{0}", fileInfo.LastWriteTimeUtc); } } int hash = stringBuilder.ToString().GetHashCode(); HttpResponse response = context.Response; HttpCachePolicy cache = response.Cache; response.ContentType = responseType.ToDescription(); cache.VaryByHeaders["Accept-Encoding"] = true; if (futureExpire) { int maxCacheDays = CruncherConfiguration.Instance.MaxCacheDays; cache.SetExpires(DateTime.UtcNow.AddDays(maxCacheDays)); cache.SetMaxAge(new TimeSpan(maxCacheDays, 0, 0, 0)); if (fileMonitors != null) { response.AddFileDependencies(fileMonitors.ToArray()); cache.SetLastModifiedFromFileDependencies(); } cache.SetValidUntilExpires(false); } else { cache.SetExpires(DateTime.UtcNow.AddDays(-1)); cache.SetMaxAge(new TimeSpan(0, 0, 0, 0)); } cache.SetRevalidation(HttpCacheRevalidation.AllCaches); string etag = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", hash); string incomingEtag = context.Request.Headers["If-None-Match"]; cache.SetETag(etag); cache.SetCacheability(HttpCacheability.Public); if (string.Compare(incomingEtag, etag, StringComparison.Ordinal) != 0) { return; } response.Clear(); response.StatusCode = (int)HttpStatusCode.NotModified; response.SuppressContent = true; }
/// <summary> /// Configures ASP.Net's Cache policy based on properties set /// </summary> /// <param name="policy">cache policy to set</param> void ICachePolicyConfigurer.Configure(HttpCachePolicy policy) { policy.SetAllowResponseInBrowserHistory(allowInHistory); policy.SetCacheability(cacheability); policy.SetOmitVaryStar(omitVaryStar); policy.SetRevalidation(revalidation); policy.SetSlidingExpiration(slidingExpiration); policy.SetValidUntilExpires(validUntilExpires); if (duration != 0) { policy.SetExpires(DateTime.Now.AddSeconds(duration)); } if (varyByContentEncodings != null) { foreach (var header in varyByContentEncodings.Split(',')) { policy.VaryByContentEncodings[header.Trim()] = true; } } if (varyByCustom != null) { policy.SetVaryByCustom(varyByCustom); } if (varyByHeaders != null) { foreach (var header in varyByHeaders.Split(',')) { policy.VaryByHeaders[header.Trim()] = true; } } if (varyByParams != null) { foreach (var param in varyByParams.Split(',')) { policy.VaryByParams[param.Trim()] = true; } } if (cacheExtension != null) { policy.AppendCacheExtension(cacheExtension); } if (setEtagFromFileDependencies) { policy.SetETagFromFileDependencies(); } if (setLastModifiedFromFileDependencies) { policy.SetLastModifiedFromFileDependencies(); } if (setNoServerCaching) { policy.SetNoServerCaching(); } if (setNoStore) { policy.SetNoStore(); } if (setNoTransforms) { policy.SetNoTransforms(); } if (etag != null) { policy.SetETag(etag); } if (isLastModifiedSet) { policy.SetLastModified(lastModified); } if (isMaxAgeSet) { policy.SetMaxAge(TimeSpan.FromSeconds(maxAge)); } if (isProxyMaxAgeSet) { policy.SetProxyMaxAge(TimeSpan.FromSeconds(proxyMaxAge)); } }
/// <summary> /// 将文件内容输出到客户端客户端浏览器,支持http头操作。 /// </summary> /// <param name="request"></param> /// <param name="response"></param> /// <param name="fileContent">要往客户端浏览器输出的文本内容</param> /// <param name="isHttpHead">True表示使用http头操作,False表示不使用http头操作</param> internal static void Output(HttpRequest request, HttpResponse response, string fileContent, string absoluteFilePath, bool isHttpHead) { if (string.IsNullOrWhiteSpace(fileContent)) { return; } //wangyunpeng 增加http头,把生成的路径输出出来,方便修改页面使用。 if (absoluteFilePath != null) { response.AddHeader("X-Page-Hash", absoluteFilePath); } HttpCachePolicy cache = response.Cache; cache.SetOmitVaryStar(true);//http://www.cnblogs.com/dudu/archive/2011/11/03/outputcache_Bug_vary.html //#if DEBUG //本地调试不使用浏览器缓存 //cache.SetCacheability(HttpCacheability.NoCache); //cache.SetExpires(DateTime.UtcNow.AddYears(-1)); //cache.SetMaxAge(TimeSpan.Zero); //cache.SetProxyMaxAge(TimeSpan.Zero); //cache.SetNoServerCaching(); //cache.SetNoStore(); //cache.SetNoTransforms(); //#else string ifModifiedSince = request.Headers["If-Modified-Since"]; if (isHttpHead) { if ( !string.IsNullOrWhiteSpace(ifModifiedSince) && TimeSpan.FromTicks(DateTime.Now.Ticks - TypeParseHelper.StrToDateTime(ifModifiedSince).Ticks).Minutes < CACHE_DATETIME) { response.StatusCode = (int)System.Net.HttpStatusCode.NotModified; response.StatusDescription = "Not Modified"; response.End(); return; } else { cache.SetLastModifiedFromFileDependencies(); cache.SetETagFromFileDependencies(); cache.SetCacheability(HttpCacheability.Public); cache.SetExpires(DateTime.UtcNow.AddMinutes(CACHE_DATETIME)); TimeSpan timeSpan = TimeSpan.FromMinutes(CACHE_DATETIME); cache.SetMaxAge(timeSpan); cache.SetProxyMaxAge(timeSpan); cache.SetLastModified(DateTime.Now); cache.SetValidUntilExpires(true); cache.SetSlidingExpiration(true); } } //#endif System.Text.Encoding encoding = IOHelper.GetHtmEncoding(fileContent) ?? NVelocityBus._GlobalizationSection.ResponseEncoding; response.ContentEncoding = encoding; response.ContentType = response.ContentType; response.Write(fileContent); //压缩页面 if (request.ServerVariables["HTTP_X_MICROSOFTAJAX"] == null) { if (NVelocityBus.IsAcceptEncoding(request, GZIP)) { response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); NVelocityBus.SetResponseEncoding(response, GZIP); } else if (NVelocityBus.IsAcceptEncoding(request, DEFLATE)) { response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); NVelocityBus.SetResponseEncoding(response, DEFLATE); } } //强制结束输出 response.End(); }