/// <summary> /// Sets the output cache parameters and also the client side caching parameters /// </summary> /// <param name="context"></param> private void SetCaching(HttpContext context, string fileName) { //This ensures OutputCaching is set for this handler and also controls //client side caching on the browser side. Default is 10 days. TimeSpan duration = TimeSpan.FromDays(10); HttpCachePolicy cache = context.Response.Cache; cache.SetCacheability(HttpCacheability.Public); cache.SetExpires(DateTime.Now.Add(duration)); cache.SetMaxAge(duration); cache.SetValidUntilExpires(true); cache.SetLastModified(DateTime.Now); cache.SetETag(Guid.NewGuid().ToString()); //set server OutputCache to vary by our params cache.VaryByParams["t"] = true; cache.VaryByParams["s"] = true; //don't allow varying by wildcard cache.SetOmitVaryStar(true); //ensure client browser maintains strict caching rules cache.AppendCacheExtension("must-revalidate, proxy-revalidate"); //This is the only way to set the max-age cachability header in ASP.Net! FieldInfo maxAgeField = cache.GetType().GetField("_maxAge", BindingFlags.Instance | BindingFlags.NonPublic); maxAgeField.SetValue(cache, duration); //make this output cache dependent on the file if there is one. if (!string.IsNullOrEmpty(fileName)) { context.Response.AddFileDependency(fileName); } }
/// <summary> /// Set the response cache headers for WebResource /// </summary> /// <param name="cache"></param> /// <param name="etag"></param> /// <param name="maxAge"></param> protected static void SetCachingHeadersForWebResource(HttpCachePolicy cache, string etag, TimeSpan maxAge) { cache.SetCacheability(HttpCacheability.Public); cache.VaryByParams["d"] = true; cache.SetOmitVaryStar(true); cache.SetExpires(DateTime.Now.Add(maxAge)); cache.SetValidUntilExpires(true); cache.VaryByHeaders["Accept-Encoding"] = true; cache.SetETag(string.Concat("\"", etag, "\"")); }
private static void OutputCacheResponse(HttpContext context, DateTime lastModified) { HttpCachePolicy cachePolicy = context.Response.Cache; cachePolicy.SetCacheability(HttpCacheability.Public); cachePolicy.VaryByParams["*"] = true; cachePolicy.SetOmitVaryStar(true); cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(365)); cachePolicy.SetValidUntilExpires(true); cachePolicy.SetLastModified(lastModified); }
private static void SetCache(HttpCachePolicy cache) { cache.SetCacheability(HttpCacheability.Public); cache.VaryByParams[_paramV] = true; cache.VaryByParams[_paramFile] = true; cache.SetOmitVaryStar(true); cache.SetValidUntilExpires(true); cache.SetExpires(DateTime.Now.AddYears(2)); cache.SetLastModified(DateTime.ParseExact(AppConstants.BuildDate, _dateFormat, CultureInfo.GetCultureInfo(_usCulture).DateTimeFormat)); }
private void SetResponseCache(HttpContext context) { HttpCachePolicy cache = context.Response.Cache; cache.SetLastModified(new DateTime(ResourceManager.GetAssemblyTime(typeof(ResourceManager).Assembly))); cache.SetOmitVaryStar(true); cache.SetVaryByCustom("v"); cache.SetExpires(DateTime.UtcNow.AddYears(1)); cache.SetMaxAge(TimeSpan.FromDays(365)); cache.SetValidUntilExpires(true); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); cache.SetCacheability(HttpCacheability.Public); }
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(); }
/// <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); }
/// <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); }
public override void SetOmitVaryStar(bool omit) { _httpCachePolicy.SetOmitVaryStar(omit); }
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 }
/// <internalonly/> void IHttpHandler.ProcessRequest(HttpContext context) { // Make sure we don't get any extra content in this handler (like Application.BeginRequest stuff); context.Response.Clear(); Stream resourceStream = null; string decryptedData = null; bool resourceIdentifierPresent = false; Exception exception = null; try { NameValueCollection queryString = context.Request.QueryString; string encryptedData = queryString["d"]; if (String.IsNullOrEmpty(encryptedData)) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest)); } resourceIdentifierPresent = true; decryptedData = Page.DecryptString(encryptedData, Purpose.AssemblyResourceLoader_WebResourceUrl); int separatorIndex = decryptedData.IndexOf('|'); Debug.Assert(separatorIndex != -1, "The decrypted data must contain a separator."); string assemblyName = decryptedData.Substring(0, separatorIndex); if (String.IsNullOrEmpty(assemblyName)) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_AssemblyNotFound, assemblyName)); } string resourceName = decryptedData.Substring(separatorIndex + 1); if (String.IsNullOrEmpty(resourceName)) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_ResourceNotFound, resourceName)); } char nameType = assemblyName[0]; assemblyName = assemblyName.Substring(1); Assembly assembly = null; // If it was a full name, create an AssemblyName and load from that if (nameType == 'f') { string[] parts = assemblyName.Split(','); if (parts.Length != 4) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest)); } AssemblyName realName = new AssemblyName(); realName.Name = parts[0]; realName.Version = new Version(parts[1]); string cultureString = parts[2]; // Try to determine the culture, using the invariant culture if there wasn't one (doesn't work without it) if (cultureString.Length > 0) { realName.CultureInfo = new CultureInfo(cultureString); } else { realName.CultureInfo = CultureInfo.InvariantCulture; } // Parse up the public key token which is represented as hex bytes in a string string token = parts[3]; byte[] tokenBytes = new byte[token.Length / 2]; for (int i = 0; i < tokenBytes.Length; i++) { tokenBytes[i] = Byte.Parse(token.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); } realName.SetPublicKeyToken(tokenBytes); assembly = Assembly.Load(realName); } // System.Web special case else if (nameType == 's') { assembly = typeof(AssemblyResourceLoader).Assembly; } // If was a partial name, just try to load it else if (nameType == 'p') { assembly = Assembly.Load(assemblyName); } else { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest)); } // Dev10 Bugs 602949: Throw 404 if resource not found rather than do nothing. // This is done before creating the cache entry, since it could be that the assembly is loaded // later on without the app restarting. if (assembly == null) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest)); } bool performSubstitution = false; bool validResource = false; string contentType = String.Empty; // Check the validation cache to see if the resource has already been validated int cacheKey = HashCodeCombiner.CombineHashCodes(assembly.GetHashCode(), resourceName.GetHashCode()); Triplet resourceTriplet = (Triplet)_webResourceCache[cacheKey]; if (resourceTriplet != null) { validResource = (bool)resourceTriplet.First; contentType = (string)resourceTriplet.Second; performSubstitution = (bool)resourceTriplet.Third; } else { // Validation cache is empty, find out if it's valid and add it to the cache WebResourceAttribute wra = FindWebResourceAttribute(assembly, resourceName); if (wra != null) { resourceName = wra.WebResource; validResource = true; contentType = wra.ContentType; performSubstitution = wra.PerformSubstitution; } // Cache the result so we don't have to do this again try { if (validResource) { // a WebResourceAttribute was found, but does the resource really exist? validResource = false; resourceStream = assembly.GetManifestResourceStream(resourceName); validResource = (resourceStream != null); } } finally { // Cache the results, even if there was an exception getting the stream, // so we don't have to do this again Triplet triplet = new Triplet(); triplet.First = validResource; triplet.Second = contentType; triplet.Third = performSubstitution; _webResourceCache[cacheKey] = triplet; } } if (validResource) { // Cache the resource so we don't keep processing the same requests HttpCachePolicy cachePolicy = context.Response.Cache; cachePolicy.SetCacheability(HttpCacheability.Public); cachePolicy.VaryByParams["d"] = true; cachePolicy.SetOmitVaryStar(true); cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(365)); cachePolicy.SetValidUntilExpires(true); Pair assemblyInfo = GetAssemblyInfo(assembly); cachePolicy.SetLastModified(new DateTime((long)assemblyInfo.Second)); StreamReader reader = null; try { if (resourceStream == null) { // null in the case that _webResourceCache had the item resourceStream = assembly.GetManifestResourceStream(resourceName); } if (resourceStream != null) { context.Response.ContentType = contentType; if (performSubstitution) { // reader = new StreamReader(resourceStream, true); string content = reader.ReadToEnd(); // Looking for something of the form: WebResource("resourcename") MatchCollection matches = webResourceRegex.Matches(content); int startIndex = 0; StringBuilder newContent = new StringBuilder(); foreach (Match match in matches) { newContent.Append(content.Substring(startIndex, match.Index - startIndex)); Group group = match.Groups["resourceName"]; if (group != null) { string embeddedResourceName = group.ToString(); if (embeddedResourceName.Length > 0) { // if (String.Equals(embeddedResourceName, resourceName, StringComparison.Ordinal)) { throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_NoCircularReferences, resourceName)); } newContent.Append(GetWebResourceUrlInternal(assembly, embeddedResourceName, htmlEncoded: false, forSubstitution: true, scriptManager: null)); } } startIndex = match.Index + match.Length; } newContent.Append(content.Substring(startIndex, content.Length - startIndex)); StreamWriter writer = new StreamWriter(context.Response.OutputStream, reader.CurrentEncoding); writer.Write(newContent.ToString()); writer.Flush(); } else { byte[] buffer = new byte[1024]; Stream outputStream = context.Response.OutputStream; int count = 1; while (count > 0) { count = resourceStream.Read(buffer, 0, 1024); outputStream.Write(buffer, 0, count); } outputStream.Flush(); } } } finally { if (reader != null) { reader.Close(); } if (resourceStream != null) { resourceStream.Close(); } } } } catch (Exception e) { exception = e; // MSRC 10405: ---- all errors in the event of failure. In particular, we don't want to // bubble the inner exceptions up in the YSOD, as they might contain sensitive cryptographic // information. Setting 'resourceStream' to null will cause an appropriate exception to // be thrown. resourceStream = null; } // Dev10 Bugs 602949: 404 if the assembly is not found or if the resource does not exist if (resourceStream == null) { if (resourceIdentifierPresent) { LogWebResourceFailure(decryptedData, exception); } throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest)); } context.Response.IgnoreFurtherWrites(); }
protected void Application_BeginRequest(Object sender, EventArgs e) { GetCultureFromRequest(); InitializeGlobalContext(); GlobalResourceManager.Initialize(HostingEnvironment.MapPath("~/App_GlobalResources/GlobalResources.xml")); string path = Request.Path; #region Remove /portals/ from query string constOldUrl = "/portals/"; if (path.IndexOf(constOldUrl, StringComparison.OrdinalIgnoreCase) >= 0) { string fullPath = Request.RawUrl; int index = fullPath.IndexOf(constOldUrl, StringComparison.OrdinalIgnoreCase); string begin = fullPath.Substring(0, index); string end = fullPath.Substring(index + constOldUrl.Length); int endOfDomain = end.IndexOf('/'); if (endOfDomain >= 0) { end = end.Substring(endOfDomain + 1); } path = begin + '/' + end; //OZ: RewritePath чтобы работали старые клиентские инструменты //AK: 2009-01-26 - exclude css if (path.EndsWith(".css", StringComparison.OrdinalIgnoreCase)) { Response.Redirect(path, true); } else { HttpContext.Current.RewritePath(path); } } #endregion bool pathContainsFiles = (path.IndexOf("/files/", StringComparison.OrdinalIgnoreCase) >= 0); bool pathContainsWebDav = (path.IndexOf("/webdav/", StringComparison.OrdinalIgnoreCase) >= 0); if (!pathContainsFiles && !pathContainsWebDav && (path.EndsWith("error.aspx", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".css", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || path.EndsWith("webresource.axd", StringComparison.OrdinalIgnoreCase) || path.EndsWith("scriptresource.axd", StringComparison.OrdinalIgnoreCase) || path.EndsWith("licenseexpired.aspx", StringComparison.OrdinalIgnoreCase) ) ) { return; } //Обработка файлов которые подвергаются кэшированию // TODO: перенести список строк и время жизни кеша в web.config if (!pathContainsFiles && !pathContainsWebDav && !path.EndsWith("Reserved.ReportViewerWebControl.axd", StringComparison.OrdinalIgnoreCase) && (path.EndsWith(".js", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".axd", StringComparison.OrdinalIgnoreCase) ) ) { HttpCachePolicy cache = HttpContext.Current.Response.Cache; //HttpContext.Current.Response.AddFileDependency(Server.MapPath(path)); bool _hanldeFlag = true; //Вид кэширования (включает возможность кэширования на прокси) cache.SetCacheability(HttpCacheability.Public); //кэширование по параметрам в QueryString (d, versionUid) //все запросы включающие любой из этих параметров будут кешироваться по значению параметра cache.VaryByParams["d"] = true; cache.VaryByParams["versionUid"] = true; cache.SetOmitVaryStar(true); //устанавливаем срок годности закэшированого файла //Можно сделать для разных типов фалов - разные сроки хранения double cacheExpires = 1; if (System.Configuration.ConfigurationManager.AppSettings["ClientCache"] != null) { cacheExpires = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["ClientCache"], CultureInfo.InvariantCulture); } cache.SetExpires(DateTime.Now + TimeSpan.FromMinutes(cacheExpires)); //cache.SetMaxAge(TimeSpan.FromSeconds(259200)); //разрешаем хранить кэш на диске cache.SetAllowResponseInBrowserHistory(true); cache.SetValidUntilExpires(true); #if (DEBUG) cache.SetExpires(DateTime.Now); cache.SetAllowResponseInBrowserHistory(false); #endif DateTime dtRequest = DateTime.MinValue; #if (!DEBUG) //проверка даты модификации файла if (File.Exists(Server.MapPath(path))) { cache.SetLastModified(File.GetLastWriteTime(Server.MapPath(path)).ToUniversalTime()); //Не удалять(!) Включает режим более строгово кеширования //Кэшеирует файлы даже после рестарта IIS, вернусь после отпуска протестирую и включу (dvs) if (HttpContext.Current.Request.Headers["If-Modified-Since"] != null) { try { dtRequest = Convert.ToDateTime(HttpContext.Current.Request.Headers["If-Modified-Since"], CultureInfo.InvariantCulture); } catch { } //если файл существует и его дата модификации совпадает с версией на клиенте то возвращаем 304, в противном случае //обрабатывать данный запрос будет дефолтный хэндлер ASP.NET (подробнее см. System.Web.Cachig.OutputCacheModule) if (File.GetLastWriteTime(Server.MapPath(path)).ToUniversalTime().ToString("r") == dtRequest.ToUniversalTime().ToString("r")) { //Если отладка загрузки скриптов включена, то не кэшируем их if ((path.EndsWith(".js", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".axd", StringComparison.OrdinalIgnoreCase)) && Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["LogSriptLoading"], CultureInfo.InvariantCulture)) { cache.SetExpires(DateTime.Now); } else { Response.ClearContent(); Response.StatusCode = 304; _hanldeFlag = false; } } } } #endif if (_hanldeFlag) { return; } } else { //25.02.2009 et: Не выполнять проверку для WebDav запросов if (!pathContainsFiles && !pathContainsWebDav) { if (path.IndexOf('\\') >= 0 || System.IO.Path.GetFullPath(Request.PhysicalPath) != Request.PhysicalPath) { throw new HttpException(404, "not found"); } } InitializeDatabase(); // Terminates request if error occurs. //AK 2009-01-16 if (!PortalConfig.SystemIsActive) { if (Request.AppRelativeCurrentExecutionFilePath.Equals("~/default.aspx", StringComparison.OrdinalIgnoreCase)) { return; } else { Response.Redirect("~/default.aspx", true); } } //Init TemplateResolver TemplateResolver.Current = new TemplateResolver(); TemplateResolver.Current.AddSource("QueryString", new TemplateSource(HttpContext.Current.Request.QueryString)); if (HttpContext.Current.Session != null) { TemplateResolver.Current.AddSource("Session", new TemplateSource(HttpContext.Current.Session)); } TemplateResolver.Current.AddSource("HttpContext", new TemplateSource(HttpContext.Current.Items)); TemplateResolver.Current.AddSource("DataContext", new TemplateSource(DataContext.Current.Attributes)); TemplateResolver.Current.AddSource("DateTime", new DateTimeTemplateSource()); TemplateResolver.Current.AddSource("Security", new Mediachase.Ibn.Data.Services.SecurityTemplateSource()); TemplateResolver.Current.AddSource("TimeTrackingSecurity", new Mediachase.IbnNext.TimeTracking.TimeTrackingSecurityTemplateSource()); //Init PathTemplateResolver PathTemplateResolver.Current = new PathTemplateResolver(); PathTemplateResolver.Current.AddSource("QueryString", new PathTemplateSource(HttpContext.Current.Request.QueryString)); if (HttpContext.Current.Session != null) { PathTemplateResolver.Current.AddSource("Session", new PathTemplateSource(HttpContext.Current.Session)); } PathTemplateResolver.Current.AddSource("HttpContext", new PathTemplateSource(HttpContext.Current.Items)); PathTemplateResolver.Current.AddSource("DataContext", new PathTemplateSource(DataContext.Current.Attributes)); PathTemplateResolver.Current.AddSource("DateTime", new Mediachase.Ibn.Web.UI.Controls.Util.DateTimePathTemplateSource()); PathTemplateResolver.Current.AddSource("Security", new Mediachase.Ibn.Web.UI.Controls.Util.SecurityPathTemplateSource()); //PathTemplateResolver.Current.AddSource("TimeTrackingSecurity", new Mediachase.IbnNext.TimeTracking.TimeTrackingSecurityTemplateSource()); // O.R. [2009-07-28]: Check license and .NET Framework version if (Configuration.WorkflowModule && WorkflowActivityWrapper.IsFramework35Installed()) { GlobalWorkflowRuntime.StartRuntime(DataContext.Current.SqlContext.ConnectionString); } } }
/// <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)); } }
public override void SetOmitVaryStar(bool omit) { _policy.SetOmitVaryStar(omit); }
/// <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 static bool OutputCombineScriptResourcesFile(HttpContext context) { bool result = false; HttpRequest request = context.Request; string text = request.QueryString["resources"]; if (!string.IsNullOrEmpty(text)) { HttpResponse response = context.Response; response.ContentType = "application/x-javascript"; HttpCachePolicy cache = response.Cache; cache.SetCacheability(HttpCacheability.Private); cache.VaryByParams["resources"] = true; cache.VaryByParams["v"] = true; cache.VaryByParams["c"] = true; cache.SetOmitVaryStar(true); cache.SetExpires(DateTime.Now.AddDays(365.0)); cache.SetValidUntilExpires(true); DateTime lastWriteTime = new FileInfo(new Uri(Assembly.GetCallingAssembly().CodeBase).LocalPath).LastWriteTime; DateTime lastModified = (DateTime.UtcNow > lastWriteTime.ToUniversalTime()) ? lastWriteTime : DateTime.Now; cache.SetLastModified(lastModified); Stream stream = response.OutputStream; if (!request.Browser.IsBrowser("IE") || 6 < request.Browser.MajorVersion) { foreach (string b in (request.Headers["Accept-Encoding"] ?? string.Empty).ToUpperInvariant().Split(new char[] { ',' })) { if ("GZIP" == b) { response.AddHeader("Content-encoding", "gzip"); stream = new GZipStream(stream, CompressionMode.Compress); break; } if ("DEFLATE" == b) { response.AddHeader("Content-encoding", "deflate"); stream = new DeflateStream(stream, CompressionMode.Compress); break; } } } CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture; CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture; try { string text2 = request.QueryString["c"]; if (!string.IsNullOrEmpty(text2)) { CultureInfo cultureInfoByIetfLanguageTag = CultureInfo.GetCultureInfoByIetfLanguageTag(text2); Thread.CurrentThread.CurrentCulture = (Thread.CurrentThread.CurrentUICulture = cultureInfoByIetfLanguageTag); } } catch (ArgumentException) { } CombinableScripts scriptByAlias = ToolkitScriptManager.CacheScriptBuckets.GetScriptByAlias(HttpUtility.UrlDecode(text), false); if (scriptByAlias != null) { using (StreamWriter streamWriter = new StreamWriter(stream)) { ToolkitScriptManager.WriteScriptsResources(scriptByAlias.Scripts, streamWriter); streamWriter.WriteLine("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();"); } result = true; } else { stream.Close(); stream = null; } Thread.CurrentThread.CurrentCulture = currentCulture; Thread.CurrentThread.CurrentUICulture = currentUICulture; } return(result); }
void IHttpHandler.ProcessRequest(HttpContext context) { context.Response.Clear(); Stream manifestResourceStream = null; try { string str = context.Request.QueryString["d"]; if (string.IsNullOrEmpty(str)) { throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_InvalidRequest")); } string str2 = Page.DecryptString(str); int index = str2.IndexOf('|'); string str3 = str2.Substring(0, index); if (string.IsNullOrEmpty(str3)) { throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_AssemblyNotFound", new object[] { str3 })); } string webResource = str2.Substring(index + 1); if (string.IsNullOrEmpty(webResource)) { throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_ResourceNotFound", new object[] { webResource })); } char ch = str3[0]; str3 = str3.Substring(1); Assembly assembly = null; switch (ch) { case 's': assembly = typeof(AssemblyResourceLoader).Assembly; break; case 'p': assembly = Assembly.Load(str3); break; case 'f': { string[] strArray = str3.Split(new char[] { ',' }); if (strArray.Length != 4) { throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_InvalidRequest")); } AssemblyName assemblyRef = new AssemblyName { Name = strArray[0], Version = new Version(strArray[1]) }; string name = strArray[2]; if (name.Length > 0) { assemblyRef.CultureInfo = new CultureInfo(name); } else { assemblyRef.CultureInfo = CultureInfo.InvariantCulture; } string str6 = strArray[3]; byte[] publicKeyToken = new byte[str6.Length / 2]; for (int i = 0; i < publicKeyToken.Length; i++) { publicKeyToken[i] = byte.Parse(str6.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); } assemblyRef.SetPublicKeyToken(publicKeyToken); assembly = Assembly.Load(assemblyRef); break; } default: throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_InvalidRequest")); } if (assembly == null) { throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_InvalidRequest")); } bool third = false; bool first = false; string second = string.Empty; int num3 = HashCodeCombiner.CombineHashCodes(assembly.GetHashCode(), webResource.GetHashCode()); Triplet triplet = (Triplet)_webResourceCache[num3]; if (triplet != null) { first = (bool)triplet.First; second = (string)triplet.Second; third = (bool)triplet.Third; } else { WebResourceAttribute attribute = FindWebResourceAttribute(assembly, webResource); if (attribute != null) { webResource = attribute.WebResource; first = true; second = attribute.ContentType; third = attribute.PerformSubstitution; } try { if (first) { first = false; manifestResourceStream = assembly.GetManifestResourceStream(webResource); first = manifestResourceStream != null; } } finally { Triplet triplet2 = new Triplet { First = first, Second = second, Third = third }; _webResourceCache[num3] = triplet2; } } if (first) { HttpCachePolicy cache = context.Response.Cache; cache.SetCacheability(HttpCacheability.Public); cache.VaryByParams["d"] = true; cache.SetOmitVaryStar(true); cache.SetExpires(DateTime.Now + TimeSpan.FromDays(365.0)); cache.SetValidUntilExpires(true); Pair assemblyInfo = GetAssemblyInfo(assembly); cache.SetLastModified(new DateTime((long)assemblyInfo.Second)); StreamReader reader = null; try { if (manifestResourceStream == null) { manifestResourceStream = assembly.GetManifestResourceStream(webResource); } if (manifestResourceStream != null) { context.Response.ContentType = second; if (third) { reader = new StreamReader(manifestResourceStream, true); string input = reader.ReadToEnd(); MatchCollection matchs = webResourceRegex.Matches(input); int startIndex = 0; StringBuilder builder = new StringBuilder(); foreach (Match match in matchs) { builder.Append(input.Substring(startIndex, match.Index - startIndex)); Group group = match.Groups["resourceName"]; if (group != null) { string a = group.ToString(); if (a.Length > 0) { if (string.Equals(a, webResource, StringComparison.Ordinal)) { throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_NoCircularReferences", new object[] { webResource })); } builder.Append(GetWebResourceUrlInternal(assembly, a, false, true, null)); } } startIndex = match.Index + match.Length; } builder.Append(input.Substring(startIndex, input.Length - startIndex)); StreamWriter writer = new StreamWriter(context.Response.OutputStream, reader.CurrentEncoding); writer.Write(builder.ToString()); writer.Flush(); } else { byte[] buffer = new byte[0x400]; Stream outputStream = context.Response.OutputStream; int count = 1; while (count > 0) { count = manifestResourceStream.Read(buffer, 0, 0x400); outputStream.Write(buffer, 0, count); } outputStream.Flush(); } } } finally { if (reader != null) { reader.Close(); } if (manifestResourceStream != null) { manifestResourceStream.Close(); } } } } catch { manifestResourceStream = null; } if (manifestResourceStream == null) { throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_InvalidRequest")); } context.Response.IgnoreFurtherWrites(); }
/// <summary> /// Specifies whether the response should contain the vary:* header when varying by parameters. /// </summary> /// <param name="omit"> /// true to direct the <see cref="T:System.Web.HttpCachePolicy" /> to not use the * value for its /// <see cref="P:System.Web.HttpCachePolicy.VaryByHeaders" /> property; otherwise, false. /// </param> public void SetOmitVaryStar(bool omit) { policy.SetOmitVaryStar(omit); }
/// <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(); }