Exemple #1
0
        /// <summary>设置缓存策略(使用context.Response.Cache来缓存输出)</summary>
        /// <remarks>
        /// ashx 的页面缓存不允许写语句:<%@ OutputCache Duration="60" VaryByParam="*" %>
        /// 故可直接调用本方法实现缓存。
        /// 参考:https://stackoverflow.com/questions/1109768/how-to-use-output-caching-on-ashx-handler
        /// </remarks>
        public static void SetCachePolicy(this HttpResponse response, int cacheSeconds, string varyByParam = "*", HttpCacheability cacheLocation = HttpCacheability.ServerAndPrivate)
        {
            HttpCachePolicy cachePolicy = response.Cache;

            if (cacheSeconds > 0)
            {
                cachePolicy.SetCacheability(cacheLocation);
                cachePolicy.SetExpires(DateTime.Now.AddSeconds((double)cacheSeconds));
                cachePolicy.SetSlidingExpiration(false);
                cachePolicy.SetValidUntilExpires(true);
                if (varyByParam.IsNotEmpty())
                {
                    cachePolicy.VaryByParams[varyByParam] = true;
                }
                else
                {
                    cachePolicy.VaryByParams.IgnoreParams = true;
                }
            }
            else
            {
                cachePolicy.SetCacheability(HttpCacheability.NoCache);
                cachePolicy.SetMaxAge(TimeSpan.Zero);
            }
        }
        /// <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>
        /// 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>
        private void SetHeaders(HttpContext context, string responseType, IEnumerable <string> dependencyPaths)
        {
            HttpResponse response = context.Response;

            response.ContentType = responseType;

            if (response.Headers["Image-Served-By"] == null)
            {
                response.AddHeader("Image-Served-By", "ImageProcessor.Web/" + AssemblyVersion);
            }

            HttpCachePolicy cache = response.Cache;

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

            context.Response.AddFileDependencies(dependencyPaths.ToArray());
            cache.SetLastModifiedFromFileDependencies();

            int maxDays = DiskCache.MaxFileCachedDuration;

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

            context.Items[CachedResponseTypeKey]        = null;
            context.Items[CachedResponseFileDependency] = null;
        }
Exemple #4
0
        /// <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>
        private void SetHeaders(HttpContext context, string responseType, IEnumerable <string> dependencyPaths)
        {
            if (this.imageCache != null)
            {
                HttpResponse response = context.Response;

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

                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();
                }

                int maxDays = this.imageCache.MaxDays;

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

                this.imageCache = null;
            }
        }
Exemple #5
0
        private static void SetCache(string path)
        {
            HttpCachePolicy cache   = HttpContext.Current.Response.Cache;
            TimeSpan        expires = TimeSpan.FromDays(14);

            cache.SetExpires(DateTime.Now.Add(expires));
            cache.SetMaxAge(expires);
            cache.SetLastModified(File.GetLastWriteTime(path));
        }
        /// <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);
        }
Exemple #7
0
        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);
        }
    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");
    }
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request      = context.Request;
            string      physicalPath = request.PhysicalPath;

            if (File.Exists(physicalPath))
            {
                string       subfix        = Path.GetExtension(physicalPath);
                bool         isOutputCache = false;
                HttpResponse response      = context.Response;
                if (".png".Equals(subfix, StringComparison.CurrentCultureIgnoreCase))
                {
                    isOutputCache        = true;
                    response.ContentType = "image/x-png";
                }
                else if (".jpg".Equals(subfix, StringComparison.CurrentCultureIgnoreCase))
                {
                    isOutputCache        = true;
                    response.ContentType = "image/pjpeg";
                }
                if (isOutputCache)
                {
                    const int DAYS            = 30;
                    string    ifModifiedSince = request.Headers["If-Modified-Since"];
                    if (!string.IsNullOrEmpty(ifModifiedSince) &&
                        TimeSpan.FromTicks(DateTime.Now.Ticks - DateTime.Parse(ifModifiedSince).Ticks).Days < DAYS)
                    {
                        response.StatusCode        = (int)System.Net.HttpStatusCode.NotModified;
                        response.StatusDescription = "Not Modified";
                        response.End();
                        return;
                    }
                    else
                    {
                        HttpCachePolicy cache = response.Cache;
                        cache.SetLastModifiedFromFileDependencies();
                        cache.SetETagFromFileDependencies();
                        cache.SetCacheability(HttpCacheability.Public);
                        cache.SetExpires(DateTime.Now.AddDays(DAYS));
                        TimeSpan timeSpan = TimeSpan.FromDays(DAYS);
                        cache.SetMaxAge(timeSpan);
                        cache.SetProxyMaxAge(timeSpan);
                        cache.SetLastModified(context.Timestamp);
                        cache.SetValidUntilExpires(true);
                        cache.SetSlidingExpiration(true);
                    }
                }
                response.WriteFile(physicalPath);
                response.End();
            }
        }
        /// <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 WebForms</remarks>
        public void CacheUntil(HttpCachePolicy 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);
        }
        /// <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);
        }
        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();
        }
        public void ProcessRequest(HttpContext context)
        {
            string[] jsFiles = context.Request.QueryString["jsfiles"].Split(',');

            List <string> files    = new List <string>();
            StringBuilder response = new StringBuilder();

            foreach (string jsFile in jsFiles)
            {
                if (!jsFile.EndsWith(".js", StringComparison.OrdinalIgnoreCase))
                {
                    //log custom exception
                    context.Response.StatusCode = 403;
                    return;
                }

                try
                {
                    JavaScriptCompressor javaScriptCompressor = new JavaScriptCompressor();
                    string filePath     = context.Server.MapPath(jsFile);
                    string js           = File.ReadAllText(filePath);
                    string compressedJS = javaScriptCompressor.Compress(js);
                    response.Append(compressedJS);
                }
                catch (Exception ex)
                {
                    //log exception
                    context.Response.StatusCode = 500;
                    return;
                }
            }

            context.Response.Write(response.ToString());

            string version = "1.0"; //your dynamic version number here

            context.Response.ContentType = "application/javascript";
            context.Response.AddFileDependencies(files.ToArray());
            HttpCachePolicy cache = context.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.VaryByParams["jsfiles"] = true;
            cache.VaryByParams["version"] = true;
            cache.SetETag(version);
            cache.SetLastModifiedFromFileDependencies();
            cache.SetMaxAge(TimeSpan.FromDays(14));
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        }
        private void OnPreSendRequestHeaders(object sender, EdgeCacheEventArgs e)
        {
            EdgeCacheRule rule = (EdgeCacheRule)sender;

            HttpContext context = e.Context;

            int minutes = rule.Duration;

            HttpResponse response = context.Response;

            HttpCachePolicy policy = response.Cache;

            policy.SetMaxAge(TimeSpan.FromMinutes(minutes));
            policy.SetCacheability(HttpCacheability.ServerAndPrivate);
            policy.SetSlidingExpiration(true);
        }
        /// <summary>
        /// When overridden in a derived class, returns a read-only stream to the virtual resource.
        /// </summary>
        /// <returns>
        /// A read-only stream to the virtual file.
        /// </returns>
        public override Stream Open()
        {
            // Set the response headers here. It's a bit hacky.
            HttpCachePolicy cache = HttpContext.Current.Response.Cache;

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

            IFileSystem azureBlobFileSystem = FileSystemProviderManager.Current.GetUnderlyingFileSystemProvider("media");
            int         maxDays             = ((AzureBlobFileSystem)azureBlobFileSystem).FileSystem.MaxDays;

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

            return(this.stream());
        }
Exemple #16
0
        private static void SetCache(bool suppressLastModified = false)
        {
            HttpContext.Current.Response.AddHeader("Age", ((int)(PortalContext.Current.LastModified - DateTime.Now).TotalSeconds).ToString(CultureInfo.InvariantCulture));
            HttpCachePolicy cache   = HttpContext.Current.Response.Cache;
            TimeSpan        expires = TimeSpan.FromDays(14);

            cache.SetExpires(DateTime.UtcNow.Add(expires));
            cache.SetMaxAge(expires);
            DateTime dt       = PortalContext.Current.LastModified;
            string   eTagDate = "\"" + dt.ToString("s", DateTimeFormatInfo.InvariantInfo) + "\"";

            HttpContext.Current.Response.AddHeader("ETag", eTagDate);

            if (!suppressLastModified)
            {
                cache.SetLastModified(PortalContext.Current.LastModified);
            }
        }
Exemple #17
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);
            }
        }
Exemple #18
0
        /// <summary>
        /// When overridden in a derived class, returns a read-only stream to the virtual resource.
        /// </summary>
        /// <returns>
        /// A read-only stream to the virtual file.
        /// </returns>
        public override Stream Open()
        {
            // Set the response headers here. It's a bit hacky.
            if (HttpContext.Current != null)
            {
                HttpCachePolicy cache = HttpContext.Current.Response.Cache;
                cache.SetCacheability(HttpCacheability.Public);
                cache.VaryByHeaders["Accept-Encoding"] = true;

                var sambaFileSystem = getFileSystem();
                int maxDays         = sambaFileSystem.FileSystem.MaxDays;

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

            return(this.getStream());
        }
Exemple #19
0
 public override void SetMaxAge(TimeSpan delta)
 {
     _httpCachePolicy.SetMaxAge(delta);
 }
            /// <summary>
            /// Sets the output cache policy for the specified domain operation entry.
            /// </summary>
            /// <param name="context">Current HttpContext</param>
            /// <param name="domainOperationEntry">The domain operation entry we need to define the cache policy for.</param>
            private static void SetOutputCachingPolicy(HttpContext context, DomainOperationEntry domainOperationEntry)
            {
                if (context == null)
                {
                    return;
                }

                if (QueryOperationInvoker.SupportsCaching(context, domainOperationEntry))
                {
                    OutputCacheAttribute outputCacheInfo = QueryOperationInvoker.GetOutputCacheInformation(domainOperationEntry);
                    if (outputCacheInfo != null)
                    {
                        HttpCachePolicy policy = context.Response.Cache;
                        if (outputCacheInfo.UseSlidingExpiration)
                        {
                            policy.SetSlidingExpiration(true);
                            policy.AddValidationCallback((HttpCacheValidateHandler) delegate(HttpContext c, object d, ref HttpValidationStatus status)
                            {
                                SlidingExpirationValidator validator = (SlidingExpirationValidator)d;
                                if (validator.IsValid())
                                {
                                    status = HttpValidationStatus.Valid;
                                }
                                else
                                {
                                    status = HttpValidationStatus.Invalid;
                                }
                            }, new SlidingExpirationValidator(outputCacheInfo.Duration));
                        }

                        if (outputCacheInfo.Duration > -1)
                        {
                            // When sliding expiration is set, ASP.NET will use the following to figure out the sliding expiration delta.
                            policy.SetExpires(DateTime.UtcNow.AddSeconds(outputCacheInfo.Duration));
                            policy.SetMaxAge(TimeSpan.FromSeconds(outputCacheInfo.Duration));
                            policy.SetValidUntilExpires(/* validUntilExpires */ true);
                        }

                        policy.SetCacheability(QueryOperationInvoker.GetCacheability(outputCacheInfo.Location));

                        if (!String.IsNullOrEmpty(outputCacheInfo.SqlCacheDependencies))
                        {
                            // Syntax is <databaseEntry>:<tableName>[;<databaseEntry>:<tableName>]*.
                            string[] dependencies = outputCacheInfo.SqlCacheDependencies.Split(QueryOperationInvoker.semiColonDelimiter, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string dependency in dependencies)
                            {
                                string[] dependencyTokens = dependency.Split(QueryOperationInvoker.colonDelimiter, StringSplitOptions.RemoveEmptyEntries);
                                if (dependencyTokens.Length != 2)
                                {
                                    throw new InvalidOperationException(Resource.DomainService_InvalidSqlDependencyFormat);
                                }

                                context.Response.AddCacheDependency(new SqlCacheDependency(dependencyTokens[0], dependencyTokens[1]));
                            }
                        }

                        if (!String.IsNullOrEmpty(outputCacheInfo.VaryByHeaders))
                        {
                            string[] headers = outputCacheInfo.VaryByHeaders.Split(QueryOperationInvoker.semiColonDelimiter, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string header in headers)
                            {
                                policy.VaryByHeaders[header] = true;
                            }
                        }

                        // The cache is based on the values of the domain operation entry's parameters.
                        foreach (DomainOperationParameter pi in domainOperationEntry.Parameters)
                        {
                            policy.VaryByParams[pi.Name] = true;
                        }

                        // We don't cache when query parameters are used. We need to vary by query parameters
                        // though such that we can intercept requests with query parameters and by-pass the cache.
                        foreach (string queryParameter in supportedQueryParameters)
                        {
                            policy.VaryByParams[queryParameter] = true;
                        }

                        return;
                    }
                }

                // By default, don't let clients/proxies cache anything.
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }
Exemple #21
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
        }