MVC 全站开启缓存,缓解服务器的请求压力

 1         protected void Application_BeginRequest()
 2         {
 3           //获取当前请求的url
 4             string url = HttpContext.Current.Request.Path;
 5             //获取请求的文件后缀名
 6             string extension = Path.GetExtension(url);
 7             //由于MVC动态页面不带后缀,所有其他有后缀的都加上缓存
 8             if (string.IsNullOrWhiteSpace(extension)) return;
 9 
10              HttpResponse Response = HttpContext.Current.Response;
11              Response.Cache.SetCacheability(HttpCacheability.Public);
12              Response.Cache.SetMaxAge(new TimeSpan(8760, 0, 0));
13              Response.Cache.SetExpires(DateTime.Now.AddYears(1));
14         }    

此举的好处就是用户在第一次访问网站后,图片,脚本,样式等其他静态资源都会被加上缓存头,只要用户不去清除本地的资源,下次访问时,浏览器就会自动判断这些静态资源的有效期,如果在有效期内就不会像服务端发起请求,缓存服务器的请求压力。但随之而来的就时每次更新静态资源,一定要在后面加上版本号,这样才会告知浏览器这是新的资源,应该向服务端请求下,否则用户还会一直看到旧资源,而不是更新后的资源。

原文地址:https://www.cnblogs.com/x1988z/p/3587740.html