Beispiel #1
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();
            }
        }
Beispiel #2
0
 public virtual void OnAuthorization(AuthorizationContext filterContext)
 {
     if (filterContext == null)
     {
         throw new ArgumentNullException("filterContext");
     }
     if (this.AuthorizeCore(filterContext.HttpContext, filterContext.AllowAnonymous))
     {
         HttpCachePolicy cache = filterContext.HttpContext.Response.Cache;
         cache.SetProxyMaxAge(new TimeSpan(0L));
         cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), filterContext.AllowAnonymous);
         return;
     }
     this.HandleUnauthorizedRequest(filterContext);
 }
        public virtual void OnAuthorization(HttpContext httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            /*
             * if ((httpContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ? true : filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)))
             * {
             *  return;
             * }
             */

            if (!this.AuthorizeCore(httpContext))
            {
                this.HandleUnauthorizedRequest(httpContext);
                return;
            }
            HttpCachePolicy cache = httpContext.Response.Cache;

            cache.SetProxyMaxAge(new TimeSpan((long)0));
            cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
        }
Beispiel #4
0
 /// <summary>
 ///     Sets the Cache-Control: s-maxage HTTP header based on the specified time span.
 /// </summary>
 /// <param name="delta">The time span used to set the Cache-Control: s-maxage header. </param>
 /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="delta" /> is less than 0. </exception>
 public void SetProxyMaxAge(TimeSpan delta)
 {
     policy.SetProxyMaxAge(delta);
 }
Beispiel #5
0
 public override void SetProxyMaxAge(TimeSpan delta)
 {
     _httpCachePolicy.SetProxyMaxAge(delta);
 }
Beispiel #6
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 #7
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 SetProxyMaxAge(TimeSpan delta)
 {
     _policy.SetProxyMaxAge(delta);
 }
Beispiel #9
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 #10
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();
        }