/// <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);
            }
        }
Пример #2
0
        /// <summary>
        /// This will make the browser and server keep the output
        /// in its cache and thereby improve performance.
        /// </summary>
        private void SetHeadersAndCache(string file, HttpContext context)
        {
            //string ext = file.Substring(file.LastIndexOf(".")).ToString().ToLower();

            //TimeSpan maxAge = new TimeSpan(3, 0, 0, 0);

            //context.Response.Cache.SetMaxAge(maxAge);

            //context.Response.AddFileDependency(file);
            //context.Response.Cache.SetCacheability(HttpCacheability.Public);

            //context.Response.Cache.VaryByParams["path"] = true;
            //context.Response.Cache.SetETagFromFileDependencies();
            //context.Response.Cache.SetExpires(DateTime.Now.AddDays(3));
            //context.Response.Expires = 86400000;
            //context.Response.Cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
            //context.Response.Cache.SetETag(string.Empty);
            //context.Response.Cache.SetLastModifiedFromFileDependencies();

            HttpResponse response = context.Response;

            TimeSpan duration = TimeSpan.FromDays(3);

            HttpCachePolicy cache = response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(duration));
            cache.SetMaxAge(duration);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");

            FieldInfo maxAgeField = cache.GetType().GetField("_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);

            maxAgeField.SetValue(cache, duration);
        }
        /// <summary>
        /// 缓存
        /// </summary>
        /// <param name="instance">HttpContext扩展</param>
        /// <param name="durationInMinutes">时间</param>
        public static void CacheKD(this HttpContext instance, int durationInMinutes)
        {
            instance.CheckOnNull("instance");
            TimeSpan        duration = TimeSpan.FromMinutes(durationInMinutes);
            HttpCachePolicy cache    = instance.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(duration));
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
            cache.SetMaxAge(duration);
        }
Пример #4
0
    public static void Cache(TimeSpan duration)
    {
        HttpCachePolicy cache = HttpContext.Current.Response.Cache;

        FieldInfo maxAgeField = cache.GetType().GetField("_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);

        maxAgeField.SetValue(cache, duration);

        cache.SetCacheability(HttpCacheability.Public);
        cache.SetExpires(DateTime.Now.Add(duration));
        cache.SetMaxAge(duration);
        cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
    }
Пример #5
0
        private void CacheResponse(HttpContext context, int durationInMinutes)
        {
            TimeSpan duration = TimeSpan.FromMinutes(durationInMinutes);

            // With the new AJAX ASMX handler, there's no need for this hack to set maxAge value

            /*FieldInfo maxAge = HttpContext.Current.Response.Cache.GetType().GetField("_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);
             * maxAge.SetValue(HttpContext.Current.Response.Cache, duration);*/

            if (context.Request.Url.AbsolutePath.EndsWith(".asmx"))
            {
                HttpCachePolicy cache = context.Response.Cache;
                cache.SetCacheability(HttpCacheability.Public);
                cache.SetExpires(DateTime.Now.Add(duration));
                cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
                cache.SetMaxAge(duration);
            }
        }
        /// <summary>
        /// This will make the browser and server keep the output
        /// in its cache and thereby improve performance.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <param name="responseType">The HTTP MIME type to send.</param>
        /// <param name="dependencyPaths">The dependency path for the cache dependency.</param>
        /// <param name="maxDays">The maximum number of days to store the image in the browser cache.</param>
        /// <param name="statusCode">An optional status code to send to the response.</param>
        public static void SetHeaders(HttpContext context, string responseType, string[] dependencyPaths, int maxDays, HttpStatusCode?statusCode = null)
        {
            HttpResponse response = context.Response;

            if (response.Headers["ImageProcessedBy"] == null)
            {
                response.AddHeader("ImageProcessedBy", $"ImageProcessor/{AssemblyVersion} - ImageProcessor.Web/{WebAssemblyVersion}");
            }

            HttpCachePolicy cache = response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.VaryByHeaders["Accept-Encoding"] = true;

            if (!string.IsNullOrWhiteSpace(responseType))
            {
                response.ContentType = responseType;
            }

            if (dependencyPaths != null)
            {
                context.Response.AddFileDependencies(dependencyPaths.ToArray());
                cache.SetLastModifiedFromFileDependencies();
            }

            if (statusCode != null)
            {
                response.StatusCode = (int)statusCode;
            }

            cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays));
            cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0));

            if (ParseCacheBuster(context.Request.QueryString))
            {
                cache.AppendCacheExtension("immutable");
            }
            else
            {
                cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            }

            AddCorsRequestHeaders(context);
        }
Пример #7
0
 /// <summary>
 ///     Appends the specified text to the Cache-Control HTTP header.
 /// </summary>
 /// <param name="extension">The text to append to the Cache-Control header. </param>
 /// <exception cref="T:System.ArgumentNullException"><paramref name="extension" /> is null. </exception>
 public void AppendCacheExtension(string extension)
 {
     policy.AppendCacheExtension(extension);
 }
Пример #8
0
 public override void AppendCacheExtension(string extension)
 {
     _httpCachePolicy.AppendCacheExtension(extension);
 }
Пример #9
0
        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
        }
Пример #10
0
        /// <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));
            }
        }