Stangray
SAP THQ Apple Nintendo Google Reynolds Amazon Yahoo

原理:

  很简单,服务器第一次向浏览器输出Head时,添加[LastModified]时间标识,浏览器再次向服务器请求时,会带上时间标识[If-Modified-Since].然后,在服务端判断时间就可以了,返回未修改304

代码:

        public static DateTime UpdateFlag = DateTime.Now;
        
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Request.Headers["If-Modified-Since"] != null)
            {
                DateTime servernow = DateTime.Now;
                DateTime.TryParse(Request.Headers["If-Modified-Since"],out servernow);
                //判断是否已过期
                if (servernow <= UpdateFlag)
                {
                    Response.StatusCode = 304;
                    Response.StatusDescription = "Not Modified";
                }
                else
                {
                    Response.Write("");//你的代码                  
                    SetClientCaching(UpdateFlag);
                }
            }
            else
            {
                //第一次访问
                Response.Write("");//你的代码
                SetClientCaching(UpdateFlag);
            }

        }
        
        /// <summary>
        /// 基于绝对时间的访问
        /// </summary>
        /// <param name="response"></param>
        /// <param name="lastModified"></param>
        private void SetClientCaching(DateTime lastModified)
        {
            Response.Cache.SetETag(lastModified.Ticks.ToString());
            Response.Cache.SetLastModified(lastModified);
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.Cache.SetMaxAge(new TimeSpan(7, 0, 0, 0));
            Response.Cache.SetSlidingExpiration(true);

        }

        /// <summary>
        /// 基于文件的访问
        /// </summary>

        /// <param name="response"></param>
        /// <param name="lastModified"></param>
        private void SetClientCaching(string fileName)
        {
            Response.AddFileDependency(fileName);
            Response.Cache.SetETagFromFileDependencies();
            Response.Cache.SetLastModifiedFromFileDependencies();
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.Cache.SetMaxAge(new TimeSpan(7, 0, 0, 0));
            Response.Cache.SetSlidingExpiration(true);
        }

posted on 2010-10-14 13:27  Stangray  阅读(869)  评论(0编辑  收藏  举报