Beispiel #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);
            }
        }
Beispiel #2
0
        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();
            }
        }
        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);
        }
Beispiel #4
0
 /// <summary>
 ///     Sets cache expiration to from absolute to sliding.
 /// </summary>
 /// <param name="slide">true or false. </param>
 public void SetSlidingExpiration(bool slide)
 {
     policy.SetSlidingExpiration(slide);
 }
Beispiel #5
0
 public override void SetSlidingExpiration(bool slide)
 {
     _httpCachePolicy.SetSlidingExpiration(slide);
 }
            /// <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);
            }
Beispiel #7
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
        }
Beispiel #8
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));
            }
        }
 public override void SetSlidingExpiration(bool slide)
 {
     _policy.SetSlidingExpiration(slide);
 }
Beispiel #10
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request     = context.Request;
            string      phyFilePath = request.PhysicalPath;

            if (!File.Exists(phyFilePath))
            {
                string phyDirPath = Path.GetDirectoryName(phyFilePath);
                if (!string.IsNullOrWhiteSpace(phyDirPath))
                {
                    string fileName = Path.GetFileNameWithoutExtension(phyFilePath);
                    if (!string.IsNullOrWhiteSpace(fileName))
                    {
                        string fileExtension = Path.GetExtension(phyFilePath);
                        if (!string.IsNullOrWhiteSpace(fileExtension))
                        {
                            string[] fileNames = fileName.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                            if (fileNames != null)
                            {
                                int length = fileNames.Length;
                                if (length > 1)
                                {
                                    fileName    = string.Join("_", fileNames, 0, length - 1);
                                    phyFilePath = Path.Combine(phyDirPath, string.Concat(fileName, fileExtension));
                                }
                                Array.Clear(fileNames, 0, length);
                                fileNames = null;
                            }
                            fileExtension = null;
                        }
                        fileName = null;
                    }
                    phyDirPath = null;
                }
            }
            if (File.Exists(phyFilePath))
            {
                HttpResponse response  = context.Response;
                ECacheType   cacheType = ECacheType.None;
                string       subfix    = Path.GetExtension(phyFilePath);
                if (".css".Equals(subfix, StringComparison.CurrentCultureIgnoreCase))
                {
                    cacheType            = ECacheType.Css;
                    response.ContentType = "text/css";
                }
                else if (".js".Equals(subfix, StringComparison.CurrentCultureIgnoreCase))
                {
                    cacheType            = ECacheType.Js;
                    response.ContentType = "application/x-javascript";
                }
#if !DEBUG
                if (cacheType != ECacheType.None)
                {
                    //http://www.cnblogs.com/shanyou/archive/2012/05/01/2477500.html
                    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
                    {
                        string fileContent = null;
                        string ifNoneMatch = request.Headers["If-None-Match"];
                        string eTag        = string.Format("\"{0}\"", this.GetFileMd5(string.Concat(phyFilePath, fileContent = this.GetFileContent(phyFilePath))));
                        if (!string.IsNullOrEmpty(ifNoneMatch) && ifNoneMatch.Equals(eTag))
                        {
                            response.StatusCode        = (int)System.Net.HttpStatusCode.NotModified;
                            response.StatusDescription = "Not Modified";
                            response.End();
                            return;
                        }
                        else
                        {
                            HttpCachePolicy cache = response.Cache;
                            //cache.SetLastModifiedFromFileDependencies();//程序自动读取文件的LastModified
                            cache.SetLastModified(context.Timestamp); //因为静态文件的URL是特殊处理过,所以程序自动读取文件是在磁盘上找不到的,故改成手工代码设置文件的LastModified的方式。wangyunpeng,2016-4-12
                            //cache.SetETagFromFileDependencies();//程序自动读取文件的ETag
                            cache.SetETag(eTag);                      //因为静态文件的URL是特殊处理过,所以程序自动读取文件是在磁盘上找不到的,故改成手工代码设置文件的ETag的方式。wangyunpeng,2016-4-12
                            cache.SetCacheability(HttpCacheability.Public);
                            cache.SetExpires(DateTime.Now.AddDays(DAYS));
                            TimeSpan timeSpan = TimeSpan.FromDays(DAYS);
                            cache.SetMaxAge(timeSpan);
                            cache.SetProxyMaxAge(timeSpan);
                            cache.SetValidUntilExpires(true);
                            cache.SetSlidingExpiration(true);
                            #region 压缩js和css文件
                            if (!string.IsNullOrWhiteSpace(fileContent))
                            {
                                if (cacheType == ECacheType.Js)
                                {
                                    string fileName = Path.GetFileName(phyFilePath);
                                    if (_MiniJsFiles.Contains(fileName, new StringComparer()))
                                    {
                                        fileContent = this.PackJavascript(fileContent);//ECMAScript压缩
                                    }
                                }
                                //输出内容
                                response.ContentEncoding = _GlobalizationSection == null ? Encoding.UTF8 : _GlobalizationSection.ResponseEncoding;
                                response.Write(fileContent);
                            }
                            #endregion
                        }
                    }
                }
                else
                {//直接输出文件
                    response.WriteFile(phyFilePath);
                }
#else
                //直接输出文件
                response.WriteFile(phyFilePath);
#endif
                //取消GZIP压缩,IE7,IE8,Safari支持GZIP压缩显示css和js有问题。wangyunpeng
                if (this.IsAcceptEncoding(request, GZIP))
                {
                    response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                    this.SetResponseEncoding(response, GZIP);
                }
                else if (this.IsAcceptEncoding(request, DEFLATE))
                {
                    response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                    this.SetResponseEncoding(response, DEFLATE);
                }
                response.End();
            }
        }
Beispiel #11
0
        /// <summary>
        /// 将文件内容输出到客户端客户端浏览器,支持http头操作。
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="fileContent">要往客户端浏览器输出的文本内容</param>
        /// <param name="isHttpHead">True表示使用http头操作,False表示不使用http头操作</param>
        internal static void Output(HttpRequest request, HttpResponse response, string fileContent, string absoluteFilePath, bool isHttpHead)
        {
            if (string.IsNullOrWhiteSpace(fileContent))
            {
                return;
            }
            //wangyunpeng 增加http头,把生成的路径输出出来,方便修改页面使用。
            if (absoluteFilePath != null)
            {
                response.AddHeader("X-Page-Hash", absoluteFilePath);
            }
            HttpCachePolicy cache = response.Cache;

            cache.SetOmitVaryStar(true);//http://www.cnblogs.com/dudu/archive/2011/11/03/outputcache_Bug_vary.html
//#if DEBUG
            //本地调试不使用浏览器缓存
            //cache.SetCacheability(HttpCacheability.NoCache);
            //cache.SetExpires(DateTime.UtcNow.AddYears(-1));
            //cache.SetMaxAge(TimeSpan.Zero);
            //cache.SetProxyMaxAge(TimeSpan.Zero);
            //cache.SetNoServerCaching();
            //cache.SetNoStore();
            //cache.SetNoTransforms();
//#else
            string ifModifiedSince = request.Headers["If-Modified-Since"];

            if (isHttpHead)
            {
                if (
                    !string.IsNullOrWhiteSpace(ifModifiedSince) &&
                    TimeSpan.FromTicks(DateTime.Now.Ticks - TypeParseHelper.StrToDateTime(ifModifiedSince).Ticks).Minutes < CACHE_DATETIME)
                {
                    response.StatusCode        = (int)System.Net.HttpStatusCode.NotModified;
                    response.StatusDescription = "Not Modified";
                    response.End();
                    return;
                }
                else
                {
                    cache.SetLastModifiedFromFileDependencies();
                    cache.SetETagFromFileDependencies();
                    cache.SetCacheability(HttpCacheability.Public);
                    cache.SetExpires(DateTime.UtcNow.AddMinutes(CACHE_DATETIME));
                    TimeSpan timeSpan = TimeSpan.FromMinutes(CACHE_DATETIME);
                    cache.SetMaxAge(timeSpan);
                    cache.SetProxyMaxAge(timeSpan);
                    cache.SetLastModified(DateTime.Now);
                    cache.SetValidUntilExpires(true);
                    cache.SetSlidingExpiration(true);
                }
            }

//#endif
            System.Text.Encoding encoding = IOHelper.GetHtmEncoding(fileContent) ?? NVelocityBus._GlobalizationSection.ResponseEncoding;
            response.ContentEncoding = encoding;
            response.ContentType     = response.ContentType;
            response.Write(fileContent);

            //压缩页面
            if (request.ServerVariables["HTTP_X_MICROSOFTAJAX"] == null)
            {
                if (NVelocityBus.IsAcceptEncoding(request, GZIP))
                {
                    response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                    NVelocityBus.SetResponseEncoding(response, GZIP);
                }
                else if (NVelocityBus.IsAcceptEncoding(request, DEFLATE))
                {
                    response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                    NVelocityBus.SetResponseEncoding(response, DEFLATE);
                }
            }
            //强制结束输出
            response.End();
        }