zoukankan      html  css  js  c++  java
  • 自定义浏览器缓存网站时间,节省网站带宽

    原理:

      很简单,服务器第一次向浏览器输出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);
            }
    
    
  • 相关阅读:
    Cefsharp支持MP4和MP3的CEF库cef.redist.x86.3.2623,对应Cefsharp49
    解读设计模式
    模拟支付宝、淘宝登录2
    模拟支付宝、淘宝登录1
    上一篇随笔是2011-11-21 17:23,唏嘘啊。。。
    像素格式
    YUV格式详解
    认识RGB和YUV
    WPF性能优化经验总结
    【日期正则表达式】
  • 原文地址:https://www.cnblogs.com/stangray/p/1851155.html
Copyright © 2011-2022 走看看