/// <summary> /// Makes the response is available in the client browser History cache, regardless of the /// <see cref="T:System.Web.HttpCacheability" /> setting made on the server, when the <paramref name="allow" /> /// parameter is true. /// </summary> /// <param name="allow"> /// true to direct the client browser to store responses in the History folder; otherwise false. The /// default is false. /// </param> public void SetAllowResponseInBrowserHistory(bool allow) { policy.SetAllowResponseInBrowserHistory(allow); }
public override void SetAllowResponseInBrowserHistory(bool allow) { _httpCachePolicy.SetAllowResponseInBrowserHistory(allow); }
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); } } }
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> /// 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)); } }