private void SetBundleHeaders(BundleResponse bundleResponse, BundleContext context)
        {
            if (context.HttpContext.Response == null)
            {
                return;
            }

            if (bundleResponse.ContentType != null)
            {
                context.HttpContext.Response.ContentType = bundleResponse.ContentType;
            }

            if (context.EnableInstrumentation || context.HttpContext.Response.Cache == null)
            {
                return;
            }

            HttpCachePolicyBase cache = context.HttpContext.Response.Cache;

            cache.SetCacheability(bundleResponse.Cacheability);
            cache.SetOmitVaryStar(true);
            cache.SetExpires(DateTime.Now.AddYears(1));
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(DateTime.Now);
            cache.VaryByHeaders["User-Agent"] = true;
        }
        protected void SetClientCacheHeader(DateTime?LastModified, string Etag, HttpCacheability CacheKind, bool ReValidate = true)
        {
            if (!EnableClientCache || LastModified == null && Etag == null)
            {
                return;
            }
            HttpCachePolicyBase cp = Response.Cache;

            cp.AppendCacheExtension("max-age=" + 3600 * MaxClientCacheAgeInHours);
            if (ReValidate)
            {
                cp.AppendCacheExtension("must-revalidate");
                cp.AppendCacheExtension("proxy-revalidate");
            }
            cp.SetCacheability(CacheKind);
            cp.SetOmitVaryStar(false);
            if (LastModified != null)
            {
                cp.SetLastModified(LastModified.Value);
            }
            cp.SetExpires(DateTime.UtcNow.AddHours(MaxClientCacheAgeInHours));
            if (Etag != null)
            {
                cp.SetETag(Etag);
            }
        }
 protected virtual void SetHttpCachePolicy(HttpCachePolicyBase policy)
 {
     policy.SetCacheability(HttpCacheability.Private);
     policy.SetExpires(DateTime.Now.Add(CacheDuration));
     policy.SetMaxAge(CacheDuration);
     policy.SetValidUntilExpires(true);
 }
Exemple #4
0
        public void Apply(HttpCachePolicyBase policy)
        {
            policy.ThrowIfNull("policy");

            if (!_hasPolicy)
            {
                return;
            }

            switch (_cacheability)
            {
            case HttpCacheability.NoCache:
                policy.SetCacheability(_allowsServerCaching == true ? HttpCacheability.ServerAndNoCache : HttpCacheability.NoCache);
                break;

            case HttpCacheability.Private:
                policy.SetCacheability(_allowsServerCaching == true ? HttpCacheability.ServerAndPrivate : HttpCacheability.Private);
                break;

            case HttpCacheability.Public:
                policy.SetCacheability(HttpCacheability.Public);
                break;
            }
            if (_noStore == true)
            {
                policy.SetNoStore();
            }
            if (_noTransforms == true)
            {
                policy.SetNoTransforms();
            }
            if (_clientCacheExpirationUtcTimestamp != null)
            {
                policy.SetExpires(_clientCacheExpirationUtcTimestamp.Value);
            }
            if (_clientCacheMaxAge != null)
            {
                policy.SetMaxAge(_clientCacheMaxAge.Value);
            }
            if (_allowResponseInBrowserHistory != null)
            {
                policy.SetAllowResponseInBrowserHistory(_allowResponseInBrowserHistory.Value);
            }
            if (_eTag != null)
            {
                policy.SetETag(_eTag);
            }
            if (_omitVaryStar != null)
            {
                policy.SetOmitVaryStar(_omitVaryStar.Value);
            }
            if (_proxyMaxAge != null)
            {
                policy.SetProxyMaxAge(_proxyMaxAge.Value);
            }
            if (_revalidation != null)
            {
                policy.SetRevalidation(_revalidation.Value);
            }
        }
Exemple #5
0
        private static void SetHeaders(BundleResponse response, BundleContext context, bool noCache)
        {
            if (context.HttpContext.Response != null)
            {
                if (response.ContentType != null)
                {
                    context.HttpContext.Response.ContentType = response.ContentType;
                }

                // Do set caching headers if instrumentation mode is on
                if (!context.EnableInstrumentation && context.HttpContext.Response.Cache != null)
                {
                    // NOTE: These caching headers were based off of what AssemblyResourceLoader does
                    // TODO: let the bundle change the caching semantics?
                    HttpCachePolicyBase cachePolicy = context.HttpContext.Response.Cache;
                    if (noCache)
                    {
                        cachePolicy.SetCacheability(HttpCacheability.NoCache);
                    }
                    else
                    {
                        cachePolicy.SetCacheability(response.Cacheability);
                        cachePolicy.SetOmitVaryStar(true);
                        cachePolicy.SetExpires(DateTime.Now.AddYears(1));
                        cachePolicy.SetValidUntilExpires(true);
                        cachePolicy.SetLastModified(DateTime.Now);
                        cachePolicy.VaryByHeaders["User-Agent"] = true;
                        // CONSIDER: Last modified logic, need to compute a hash of all the dates/ETag support
                    }
                }
            }
        }
        /// <summary>
        /// Set HTTP cache headers based on data passed in.
        /// </summary>
        /// <param name="relativeToDate">The start date cache time spans are relative to, usually <see cref="DateTime.UtcNow"/>.</param>
        /// <param name="defaultCachePeriod">The default cache period.</param>
        /// <param name="contentExpiryDates">Expiry dates for any content, either part of a page or the whole page.</param>
        /// <param name="isPreview">if set to <c>true</c> [is preview].</param>
        /// <param name="cachePolicy">The cache policy.</param>
        private void SetHttpCacheHeaders(DateTime relativeToDate, TimeSpan defaultCachePeriod, IList <DateTime> contentExpiryDates, bool isPreview, HttpCachePolicyBase cachePolicy)
        {
            // Only do this if it's enabled in web.config
            if (!IsHttpCachingEnabled())
            {
                return;
            }

            // Never use HTTP caching for anyone who can edit the site
            if (isPreview)
            {
                cachePolicy.SetCacheability(HttpCacheability.NoCache);
                cachePolicy.SetMaxAge(new TimeSpan(0));
                cachePolicy.AppendCacheExtension("must-revalidate, proxy-revalidate");
            }
            else
            {
                // Get cache period.
                var freshness = WorkOutCacheFreshness(relativeToDate, defaultCachePeriod, contentExpiryDates);

                // Cache the page
                // Use "private" setting so that shared caches aren't used, because shared caches might cache the mobile view and serve it to a desktop user.
                // "Vary: User-Agent" should be the best way to prevent that, but .NET converts it to "Vary: *" which effectively prevents caching.
                cachePolicy.SetCacheability(HttpCacheability.Private);
                cachePolicy.SetExpires(freshness.FreshUntil.ToUniversalTime());
                cachePolicy.SetMaxAge(freshness.FreshFor);
            }
        }
Exemple #7
0
        /*public HashSet<string> Endings { get; set; }
         *
         * private bool ContainsEnding(string ending) {
         *  return ending != null && Endings.Contains(ending);
         * }*/

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Duration.TotalMilliseconds <= 0)
            {
                return;
            }

            /* Uri url = filterContext.HttpContext.Request.Url;
             * string localPath = url != null
             *                     ? url.LocalPath.ToLowerInvariant()
             *                     : null;
             * if (string.IsNullOrEmpty(localPath)) {
             *  return;
             * }
             * if (EnumerableValidator.IsNotNullAndNotEmpty(Endings)) {
             *  string fileName = Path.GetFileName(localPath);
             *  string extension = Path.GetExtension(localPath);
             *  if (!ContainsEnding(fileName) && !ContainsEnding(extension)) {
             *      //файл не подходит под искомую маску
             *      return;
             *  }
             *
             *  //файл подошел под искомую маску - установить время кэша
             * }*/

            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(Duration));
            cache.SetMaxAge(Duration);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
        }
        public override void OnActionExecuted(
            ActionExecutedContext filterContext)
        {
            if (Duration < 0)
            {
                return;
            }

            HttpCachePolicyBase cache = filterContext.HttpContext
                                        .Response.Cache;

            if (PreventBrowserCaching)
            {
                cache.SetCacheability(HttpCacheability.NoCache);
                Duration = 0;
            }
            else
            {
                cache.SetCacheability(HttpCacheability.Public);
            }

            TimeSpan cacheDuration = TimeSpan.FromSeconds(Duration);

            cache.SetExpires(DateTime.Now.Add(cacheDuration));
            cache.SetMaxAge(cacheDuration);
            cache.AppendCacheExtension("must-revalidate,"
                                       + "proxy-revalidate");
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var acDomain = filterContext.HttpContext.Application[Constants.ApplicationRuntime.AcDomainCacheKey] as IAcDomain;

            if (Enable || acDomain.Config.EnableClientCache)
            {
                if (Duration <= 0)
                {
                    return;
                }

                HttpCachePolicyBase cache         = filterContext.HttpContext.Response.Cache;
                TimeSpan            cacheDuration = TimeSpan.FromSeconds(Duration);

                cache.SetCacheability(HttpCacheability.Public);
                cache.SetExpires(DateTime.Now.Add(cacheDuration));
                if (!string.IsNullOrEmpty(VaryByParam))
                {
                    string[] parms = VaryByParam.Split(';');
                    foreach (var parm in parms)
                    {
                        cache.VaryByParams[parm] = true;
                    }
                }
                cache.SetMaxAge(cacheDuration);
                cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
            }
        }
Exemple #10
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

            // 在關閉瀏覽器或者切換使用者時,刪除快取資料 (http://blog.toright.com/posts/3414/初探-http-1-1-cache-機制.html)
            cache.SetCacheability(HttpCacheability.Public);

            // 在 http response header 裡設 expire time 減少 client 送出 http request (http://fcamel-life.blogspot.tw/2010/06/http-response-header-expire-request.html)
            cache.SetExpires(DateTime.Now.AddDays(365)); // HTTP/1.0
            // filterContext.HttpContext.Response.Cache.SetValidUntilExpires(true);

            cache.SetMaxAge(TimeSpan.FromDays(365));      // HTTP/1.1, Cache-Control: max-age
            cache.SetProxyMaxAge(TimeSpan.FromDays(365)); // HTTP/1.1, Cache-Control: s-maxage

            cache.SetETagFromFileDependencies();
            cache.SetLastModifiedFromFileDependencies();
            cache.SetAllowResponseInBrowserHistory(true);

            // http://stackoverflow.com/questions/6151292/httpcontext-current-response-cache-setcacheabilityhttpcacheability-nocache-not
            // 按下登出按鈕所需要的快取設定
            //cache.SetCacheability(HttpCacheability.NoCache);
            //cache.SetExpires(DateTime.UtcNow.AddHours(-1));
            //cache.SetNoStore();

            // http://stackoverflow.com/questions/4078011/how-to-switch-off-caching-for-mvc-requests-but-not-for-static-files-in-iis7
            // 關閉 Cache 功能
            //cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            //cache.SetValidUntilExpires(false);
            //cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            //cache.SetCacheability(HttpCacheability.NoCache);
            //cache.SetNoStore();
        }
        protected virtual void SetCache(HttpResponseBase response, int cacheDuration, params string[] varyByParams)
        {
            // Cache
            if (cacheDuration > 0)
            {
                DateTime timestamp = DateTime.Now;

                HttpCachePolicyBase cache = response.Cache;
                int duration = cacheDuration;

                cache.SetCacheability(HttpCacheability.Public);
                cache.SetAllowResponseInBrowserHistory(true);
                cache.SetExpires(timestamp.AddSeconds(duration));
                cache.SetMaxAge(new TimeSpan(0, 0, duration));
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(timestamp);
                cache.VaryByHeaders["Accept-Encoding"] = true;
                if (varyByParams != null)
                {
                    foreach (var p in varyByParams)
                    {
                        cache.VaryByParams[p] = true;
                    }
                }

                cache.SetOmitVaryStar(true);
                response.AddHeader("Cache-Control", string.Format("public, max-age={0}", cacheDuration));
            }
        }
		protected virtual void SetHttpCachePolicy(HttpCachePolicyBase policy)
		{
			policy.SetCacheability(HttpCacheability.Private);
			policy.SetExpires(DateTime.Now.Add(CacheDuration));
			policy.SetMaxAge(CacheDuration);
			policy.SetValidUntilExpires(true);
		}
Exemple #13
0
 public override void SetCache(HttpCachePolicyBase cache)
 {
     if (null != cache)
     {
         cache.SetCacheability(HttpCacheability.Server);
         cache.SetExpires(DateTime.UtcNow.AddDays(1));
     }
 }
 private static void InvalidateCache(HttpCachePolicyBase cache)
 {
     cache.SetExpires(DateTime.UtcNow.AddDays(-1));
     cache.SetValidUntilExpires(false);
     cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
     cache.SetCacheability(HttpCacheability.NoCache);
     cache.SetNoStore();
 }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

            cache.SetCacheability(_cacheability);
            cache.SetExpires(DateTime.Now);
            cache.SetAllowResponseInBrowserHistory(false);
        }
 protected virtual void SetHttpCachePolicy(HttpCachePolicyBase policy, TemplateInfo info)
 {
     policy.SetCacheability(info.Cacheability);
     policy.SetExpires(DateTime.Now.AddMinutes(info.CacheDuration));
     policy.SetMaxAge(TimeSpan.FromMinutes(info.CacheDuration));
     policy.SetValidUntilExpires(true);
     policy.SetETagFromFileDependencies();
     policy.SetLastModifiedFromFileDependencies();
 }
Exemple #17
0
 public override void OnResultExecuted(ResultExecutedContext filterContext)
 {
     if (filterContext.HttpContext.Request.IsAjaxRequest())
     {
         HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
         cache.SetExpires(DateTime.UtcNow.AddDays(-1));
         cache.SetCacheability(HttpCacheability.NoCache);
         cache.SetNoStore();
     }
 }
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

        cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        cache.SetValidUntilExpires(false);
        cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        cache.SetCacheability(HttpCacheability.NoCache);
        cache.SetNoStore();
    }
        public override void SetCache(HttpCachePolicyBase cache)
        {
            if (null == cache)
            {
                throw new ArgumentNullException("cache");
            }

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(Expires);
        }
        public static void CacheResponseFor(this HttpContextBase context, TimeSpan duration)
        {
            HttpCachePolicyBase cache = context.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetLastModified(context.Timestamp);
            cache.SetExpires(context.Timestamp.Add(duration));
            cache.SetMaxAge(duration);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        }
        private void AddNoOutputCacheHeaders(AuthorizationContext filterContext)
        {
            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;

            cachePolicy.SetExpires(DateTime.UtcNow.AddDays(-1));
            cachePolicy.SetValidUntilExpires(false);
            cachePolicy.AppendCacheExtension("must-revalidate, proxy-revalidate");
            cachePolicy.SetCacheability(HttpCacheability.NoCache);
            cachePolicy.SetNoStore();
        }
Exemple #22
0
        private static void PrepareResponseNoCache(HttpResponseBase response)
        {
            HttpCachePolicyBase cachePolicy = response.Cache;
            DateTime            now         = DateTime.Now;

            cachePolicy.SetCacheability(HttpCacheability.Public);
            cachePolicy.SetExpires(now + TimeSpan.FromDays(365));
            cachePolicy.SetValidUntilExpires(true);
            cachePolicy.SetLastModified(now);
            cachePolicy.SetNoServerCaching();
        }
Exemple #23
0
        private static void PrepareResponseCache(HttpResponseBase response)
        {
            HttpCachePolicyBase cachePolicy = response.Cache;
            DateTime            now         = DateTime.Now;

            cachePolicy.SetCacheability(HttpCacheability.Public);
            cachePolicy.VaryByParams["d"] = true;
            cachePolicy.SetOmitVaryStar(true);
            cachePolicy.SetExpires(now + TimeSpan.FromDays(365));
            cachePolicy.SetValidUntilExpires(true);
            cachePolicy.SetLastModified(now);
        }
Exemple #24
0
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

            cache.SetCacheability(HttpCacheability.NoCache);

            cache.SetCacheability(HttpCacheability.NoCache);
            cache.SetExpires(DateTime.UtcNow.AddHours(-1));
            cache.SetNoStore();

            base.OnResultExecuted(filterContext);
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            HttpCachePolicyBase cache         = filterContext.HttpContext.Response.Cache;
            TimeSpan            cacheDuration = new TimeSpan(180, 0, 0, 0);

            cache.SetCacheability(HttpCacheability.Private);
            cache.SetExpires(DateTime.Now.Add(cacheDuration));
            cache.SetMaxAge(cacheDuration);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
        }
        /// <summary>
        /// Caches the specified instance.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="duration">The duration.</param>
        public static void Cache(this HttpContextBase instance, TimeSpan duration)
        {
            HttpCachePolicyBase 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);
        }
Exemple #27
0
 /// <summary>
 /// It is better to detect controller and action rather than plain url (such as "/Home/Index", "/Home", "/" since routes are equal by default).
 /// </summary>
 public void DetectConfiguration(string url, HttpCachePolicyBase cachePolicy)
 {
     if (url == "/CodeCaching/Index")
     {
         cachePolicy.SetNoServerCaching();
         cachePolicy.SetCacheability(HttpCacheability.NoCache);
     }
     else
     {
         cachePolicy.SetExpires(DateTime.Now.AddSeconds(30));
         cachePolicy.SetCacheability(HttpCacheability.Public);
     }
 }
        public new void OnResultExecuted(ResultExecutedContext filterContext)
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;

            cache.SetCacheability(HttpCacheability.NoCache);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetValidUntilExpires(false);
            cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            cache.SetNoStore();
            cache.AppendCacheExtension("private");
            cache.AppendCacheExtension("no-cache=Set-Cookie");
            cache.SetProxyMaxAge(TimeSpan.Zero);
        }
        /// <summary>
        /// Sets a response to be cached for a given amount of time following the initial request, allowing both shared and private caches
        /// </summary>
        /// <param name="cachePolicy">The response.</param>
        /// <param name="currentTime">The current time.</param>
        /// <param name="cacheExpiryTime">The cache expiry time.</param>
        /// <param name="responseIsIdenticalForEveryUser">if set to <c>true</c> one user may receive a response that was prepared for another user.</param>
        /// <exception cref="System.ArgumentNullException">cachePolicy</exception>
        /// <remarks>This method is for use with ASP.NET MVC</remarks>
        public void CacheUntil(HttpCachePolicyBase cachePolicy, DateTime currentTime, DateTime cacheExpiryTime, bool responseIsIdenticalForEveryUser = true)
        {
            if (cachePolicy == null)
            {
                throw new ArgumentNullException("cachePolicy");
            }

            // Max-Age is the current standard, and Expires is the older one
            cachePolicy.SetMaxAge(cacheExpiryTime.Subtract(currentTime));
            cachePolicy.SetExpires(cacheExpiryTime);

            // Public allows caching on shared proxies as well as users' own browsers
            cachePolicy.SetCacheability(responseIsIdenticalForEveryUser ? HttpCacheability.Public : HttpCacheability.Private);
        }
Exemple #30
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (Duration <= 0)
            {
                return;
            }

            HttpCachePolicyBase cache         = filterContext.HttpContext.Response.Cache;
            TimeSpan            cacheDuration = TimeSpan.FromMinutes(Duration);

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(cacheDuration));
            cache.SetMaxAge(cacheDuration);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
        }
Exemple #31
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (Day <= 0)
            {
                return;
            }
            HttpCachePolicyBase cache    = filterContext.HttpContext.Response.Cache;
            TimeSpan            Duration = TimeSpan.FromDays(Day);

            cache.SetExpires(DateTime.Now.Add(Duration));
            cache.SetMaxAge(Duration);
            cache.SetLastModified(DateTime.Now);
            cache.SetCacheability(Cacheability);
            base.OnActionExecuted(filterContext);
        }
        internal static void OutputCache(HttpContextBase httpContext,
                                         HttpCachePolicyBase cache,
                                         int numberOfSeconds,
                                         bool sliding,
                                         IEnumerable<string> varyByParams,
                                         IEnumerable<string> varyByHeaders,
                                         IEnumerable<string> varyByContentEncodings,
                                         HttpCacheability cacheability)
        {
            cache.SetCacheability(cacheability);
            cache.SetExpires(httpContext.Timestamp.AddSeconds(numberOfSeconds));
            cache.SetMaxAge(new TimeSpan(0, 0, numberOfSeconds));
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(httpContext.Timestamp);
            cache.SetSlidingExpiration(sliding);

            if (varyByParams != null)
            {
                foreach (var p in varyByParams)
                {
                    cache.VaryByParams[p] = true;
                }
            }

            if (varyByHeaders != null)
            {
                foreach (var headerName in varyByHeaders)
                {
                    cache.VaryByHeaders[headerName] = true;
                }
            }

            if (varyByContentEncodings != null)
            {
                foreach (var contentEncoding in varyByContentEncodings)
                {
                    cache.VaryByContentEncodings[contentEncoding] = true;
                }
            }
        }
		protected virtual void SetHttpCachePolicy(HttpCachePolicyBase policy, TemplateInfo info)
		{
			policy.SetCacheability(info.Cacheability);
			policy.SetExpires(DateTime.Now.AddMinutes(info.CacheDuration));
			policy.SetMaxAge(TimeSpan.FromMinutes(info.CacheDuration));
			policy.SetValidUntilExpires(true);
			policy.SetETagFromFileDependencies();
			policy.SetLastModifiedFromFileDependencies();
		}