/// <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);
            }
        }
		protected virtual void SetHttpCachePolicy(HttpCachePolicyBase policy)
		{
			policy.SetCacheability(HttpCacheability.Private);
			policy.SetExpires(DateTime.Now.Add(CacheDuration));
			policy.SetMaxAge(CacheDuration);
			policy.SetValidUntilExpires(true);
		}
 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 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();
        }
        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");
        }
Exemple #6
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 #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");
        }
        /// <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");
            }
        }
        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, 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();
 }
        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 HandleCaching(HttpCachePolicyBase cache, string etag)
 {
     cache.SetCacheability(System.Web.HttpCacheability.Public);
     //cache.SetExpires(DateTime.Now.AddDays(7));
     cache.SetMaxAge(TimeSpan.FromDays(7));
     cache.SetETag(etag);
     //cache.SetValidUntilExpires(false);
     cache.VaryByParams["id"]   = true;
     cache.VaryByParams["size"] = true;
     //cache.SetLastModified(DateTime.SpecifyKind(picture.UpdatedOnUtc, DateTimeKind.Utc));
 }
        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);
        }
        /// <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 #16
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");
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if ((MZHelperConfiguration.MZCacheTime <= 0) || !MZHelperConfiguration.MZEnableMinify)
            {
                return;
            }

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

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(cacheDuration));
            cache.SetMaxAge(cacheDuration);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
        }
Exemple #18
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);
        }
        /// <summary>
        /// Set the caching policy.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="duration">The duration.</param>
        public void Cache(HttpContextBase context, TimeSpan duration)
        {
            if ((duration > TimeSpan.Zero) || !context.IsDebuggingEnabled) // Do not cache in debug mode.
            {
                HttpCachePolicyBase cache = context.Response.Cache;

                cache.SetCacheability(HttpCacheability.Public);
                cache.SetOmitVaryStar(true);
                cache.SetExpires(context.Timestamp.Add(duration));
                cache.SetMaxAge(duration);
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(context.Timestamp);
                cache.SetLastModifiedFromFileDependencies();
                cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            }
        }
Exemple #20
0
        /// <summary>
        /// action执行后
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (this._MaxSecond <= 0)
            {
                return;
            }

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

            cache.SetCacheability(HttpCacheability.Public);
            //cache.SetLastModified(DateTime.Now.AddHours(8).Add(cacheDuration));
            //cache.SetExpires(DateTime.Now.AddHours(8).Add(cacheDuration));//GMT时间 格林威治时间
            cache.SetExpires(DateTime.Now.Add(cacheDuration));
            cache.SetMaxAge(cacheDuration);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
        }
Exemple #21
0
        public static void OutputCache(this HttpResponseBase response,
                                       int numberOfSeconds,
                                       bool sliding = false,
                                       IEnumerable <string> varyByParams           = null,
                                       IEnumerable <string> varyByHeaders          = null,
                                       IEnumerable <string> varyByContentEncodings = null,
                                       HttpCacheability cacheability = HttpCacheability.Public)
        {
            HttpCachePolicyBase cache = response.Cache;

            var context = HttpContext.Current;

            cache.SetCacheability(cacheability);
            cache.SetExpires(context.Timestamp.AddSeconds(numberOfSeconds));
            cache.SetMaxAge(new TimeSpan(0, 0, numberOfSeconds));
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(context.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;
                }
            }
        }
Exemple #22
0
        protected override void SendMediaHeaders(Media media, HttpContextBase context)
        {
            GetResponseCacheHeadersArgs args = new GetResponseCacheHeadersArgs(media.MediaData.MediaItem.InnerItem, new ResponseCacheHeaders()
            {
                Vary = this.GetVaryHeader(media, context)
            })
            {
                RequestType = new RequestTypes?(RequestTypes.Media)
            };

            GetResponseCacheHeadersPipeline.Run(args);
            HttpCachePolicyBase cache = context.Response.Cache;

            if (args.CacheHeaders.LastModifiedDate.HasValue)
            {
                cache.SetLastModified(args.CacheHeaders.LastModifiedDate.Value);
            }
            if (!string.IsNullOrEmpty(args.CacheHeaders.ETag))
            {
                cache.SetETag(args.CacheHeaders.ETag);
            }
            if (args.CacheHeaders.Cacheability.HasValue)
            {
                cache.SetCacheability(args.CacheHeaders.Cacheability.Value);
            }
            if (args.CacheHeaders.MaxAge.HasValue)
            {
                cache.SetMaxAge(args.CacheHeaders.MaxAge.Value);
            }
            if (args.CacheHeaders.ExpirationDate.HasValue)
            {
                cache.SetExpires(args.CacheHeaders.ExpirationDate.Value);
            }
            if (!string.IsNullOrEmpty(args.CacheHeaders.CacheExtension))
            {
                cache.AppendCacheExtension(args.CacheHeaders.CacheExtension);
            }
            if (string.IsNullOrEmpty(args.CacheHeaders.Vary))
            {
                return;
            }
            context.Response.AppendHeader("vary", args.CacheHeaders.Vary);
        }
Exemple #23
0
        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;
                }
            }
        }
        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;
                }
            }
        }
 private void SetCache(HttpCachePolicyBase cache, System.Net.Http.Headers.CacheControlHeaderValue cacheIn)
 {
     if (cacheIn.Public)
     {
         cache.SetCacheability(HttpCacheability.Public);
     }
     if (cacheIn.Private)
     {
         cache.SetCacheability(HttpCacheability.Private);
     }
     if (cacheIn.MaxAge != null)
     {
         var maxAge = cacheIn.MaxAge.Value;
         if (maxAge.TotalDays < 1)
         {
             maxAge = TimeSpan.FromDays(30);
         }
         cache.SetCacheability(HttpCacheability.Public);
         cache.SetMaxAge(maxAge);
         cache.SetSlidingExpiration(true);
     }
 }
Exemple #26
0
        protected void SendOuptToClient(HttpContextBase context)
        {
            HttpResponseBase    response = context.Response;
            HttpCachePolicyBase cache    = context.Response.Cache;

            cache.SetETag(_etagCacheKey);
            cache.SetLastModified(_lastModify);
            cache.SetExpires(NetworkTime.Now.AddDays(_durationInDays)); // For HTTP 1.0 browsers
            cache.SetOmitVaryStar(true);
            cache.SetMaxAge(TimeSpan.FromDays(_durationInDays));
            //cache.SetLastModified(NetworkTime.Now);

            cache.SetValidUntilExpires(true);
            cache.SetCacheability(HttpCacheability.Public);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.VaryByHeaders["Accept-Encoding"] = true;// Tell proxy to cache different versions depending on Accept-Encoding
            response.ContentType = "application/json";
            if (response.IsClientConnected)
            {
                response.Flush();
            }
        }
Exemple #27
0
        public string Index(string id)
        {
            HttpCachePolicyBase cache         = HttpContext.Response.Cache;
            TimeSpan            cacheDuration = TimeSpan.FromSeconds(60);

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(cacheDuration));
            cache.SetMaxAge(cacheDuration);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
            Response.ContentType = "text/cache-manifest";
            var model      = new AppCacheViewModel(Url, id);
            var appversion = ConfigurationManager.AppSettings[id];
            var version    = "v=" + appversion + " a=" + typeof(AppCacheController).Assembly.GetName().Version.ToString();

            if (string.IsNullOrEmpty(appversion))
            {
                version = "a=" + typeof(AppCacheController).Assembly.GetName().Version.ToString();
            }

            model.PageComment = id + " cache version : " + version;

            return(RenderRazorViewToString("Index", model));
        }
Exemple #28
0
        public static void Apply(this HttpCacheOptions options, HttpCachePolicyBase policy)
        {
            if (policy == null)
            {
                return;
            }

            policy.SetCacheability(options.IsPublic ? HttpCacheability.Public : HttpCacheability.Private);

            if (options.LastModified.HasValue)
            {
                policy.SetLastModified(options.LastModified.Value);
            }

            if (!string.IsNullOrEmpty(options.ETag))
            {
                policy.SetETag(options.QuotedETag);
            }

            if (options.MaxAge.HasValue)
            {
                policy.SetMaxAge(options.MaxAge.Value);
            }
        }
Exemple #29
0
 /// <summary>
 /// 设置缓存过期时间
 /// </summary>
 /// <param name="delta">从当前开始最大的过期时间</param>
 public override void SetMaxAge(TimeSpan delta)
 {
     _cachePolicy.SetMaxAge(delta);
 }
        public void Index(string name, string version, string condition)
        {
            HttpResponseBase response = Response;

            WebResourcesSection section = ConfigurationManager.GetSection(Kooboo.Common.Web.AreaHelpers.GetAreaName(this.RouteData));

            if (section == null)
            {
                throw new HttpException(500, "Unable to find the web resource configuration.");
            }

            ReferenceElement settings = section.References[name];

            if (settings == null)
            {
                throw new HttpException(500, string.Format("Unable to find any matching web resource settings for {0}.", name));
            }

            Condition conditionInfo = new Condition
            {
                If = condition ?? string.Empty
            };

            // filter the files based on the condition (Action / If) passed in
            IList <FileInfoElement> files = new List <FileInfoElement>();

            foreach (FileInfoElement fileInfo in settings.Files)
            {
                if (fileInfo.If.Equals(conditionInfo.If))
                {
                    files.Add(fileInfo);
                }
            }

            // Ooutput Type
            response.ContentType = settings.MimeType;
            Stream output = response.OutputStream;

            // Compress
            if (section.Compress)
            {
                string acceptEncoding = Request.Headers["Accept-Encoding"];

                if (!string.IsNullOrEmpty(acceptEncoding))
                {
                    acceptEncoding = acceptEncoding.ToLowerInvariant();

                    if (acceptEncoding.Contains("gzip"))
                    {
                        response.AddHeader("Content-encoding", "gzip");
                        output = new GZipStream(output, CompressionMode.Compress);
                    }
                    else if (acceptEncoding.Contains("deflate"))
                    {
                        response.AddHeader("Content-encoding", "deflate");
                        output = new DeflateStream(output, CompressionMode.Compress);
                    }
                }
            }

            // Combine
            using (StreamWriter sw = new StreamWriter(output))
            {
                foreach (FileInfoElement fileInfo in files)
                {
                    string content;
                    var    dynamicResource = DynamicClientResourceFactory.Default.ResolveProvider(fileInfo.Filename);

                    if (dynamicResource != null)
                    {
                        content = dynamicResource.Parse(fileInfo.Filename);
                    }
                    else
                    {
                        content = System.IO.File.ReadAllText(Server.MapPath(fileInfo.Filename));
                    }
                    switch (settings.MimeType)
                    {
                    case "text/css":
                        content = CSSMinify.Minify(Url, fileInfo.Filename, Request.Url.AbsolutePath, content);
                        break;

                    case "text/x-javascript":
                    case "text/javascript":
                    case "text/ecmascript":
                        if (section.Compact && fileInfo.Compact)
                        {
                            content = JSMinify.Minify(content);
                        }
                        break;
                    }
                    sw.WriteLine(content.Trim());
                }
            }

            // Cache

            if (section.CacheDuration > 0)
            {
                DateTime            timestamp = HttpContext.Timestamp;
                HttpCachePolicyBase cache     = response.Cache;
                int duration = section.CacheDuration;

                cache.SetCacheability(HttpCacheability.Public);
                cache.SetExpires(timestamp.AddSeconds(duration));
                cache.SetMaxAge(new TimeSpan(0, 0, duration));
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(timestamp);
                cache.VaryByHeaders["Accept-Encoding"] = true;
                cache.VaryByParams["name"]             = true;
                cache.VaryByParams["version"]          = true;
                cache.VaryByParams["display"]          = true;
                cache.VaryByParams["condition"]        = true;
                cache.SetOmitVaryStar(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();
		}