关于asp.net 缓存JS,CSS,图片等不经常变动的文件。
弄了个小网站,发现数据库展示的信息小,JS CSS 图片很多,而且由于网站背景这些东西可能 几年都不会变,遂想把这些不变的东西缓存到客户端存他一个月更新一次。
1,办法是改IIS设置启用IIS的过期功能。但是这样的方法不实用,一般都把网站放在服务商哪儿,不能改IIS 。
2,写代码设置缓存写个类继承IHttpHandler,在配置文件里配置要监视客户端的请求文件类型。
context.Response.Cache.SetExpires(DateTime.Now.Add(new TimeSpan(7,0,0,0))); context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.SetValidUntilExpires(false); switch (extension) { case "jpg": context.Response.ContentType = "image/jpeg"; break; case "png": context.Response.ContentType = "image/png"; break; case "gif": context.Response.ContentType = "image/gif"; break; case "swf": context.Response.ContentType = "application/x-shockwave-flash"; break; case "css": context.Response.ContentType = "text/css"; break; case "js": context.Response.ContentType = "application/x-javascript"; break; } context.Response.AddHeader("content-disposition", "inline; filename=" + filename); context.Response.WriteFile(file); }