Microsoft Visual Studio2012 MVC3.0
要使用HTTP页面缓存欠侵冲实际上就是对Response.Cache的使用,下面我们来看代码:protected ActionResult Page_Load(object sender, EventArgs e){ TimeSpan cacheDuration = new TimeSpan(24, 0, 0); System.Reflection.FieldInfo maxAge = System.Web.HttpContext.Current.Response.Cache.GetType().GetField('_maxAge', System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); maxAge.SetValue(System.Web.HttpContext.Current.Response.Cache, cacheDuration); System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public); System.Web.HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.Add(cacheDuration)); System.Web.HttpContext.Current.Response.Cache.AppendCacheExtension('max-age=' + cacheDuration.TotalSeconds + ''); System.Web.HttpContext.Current.Response.Cache.SetETag(strReturn.Length.ToString()); return View();}上面的代码基本上就可以实现缓存了,然后让我们来看以下效果图:
下面我们来看一下实现304应答的代码: public ActionResult Page_Load(object sender, EventArgs e) { DateTime dt; if( DateTime.TryParse(Request.Headers['If-Modified-Since'], out dt) ) { if( (DateTime.Now - dt).TotalSeconds < 60.0 ) { Response.StatusCode = 304; Response.End(); return; } } Response.Cache.SetLastModified(DateTime.Now); return View(); }当用户第一次请求页面时,会调用Response.Cache.SetLastModified,它会在响应时输出一个'Last-Modified'这个响应头, 然后,当浏览器再次访问这个页面时,会将上次请求所获取的'Last-Modified'头宿陵的内容 , 以'If-Modified-Since'这个请求头的形式发给服务端,此时服务器就可以根据具体逻辑来判断肤场要不要使用304应答了。上面代码我们判断如果是60秒以内我们就以304方式响应。下面我们来看以下效果图:
很显然上图的状态变成了'304 Not Modified' 这个时候即使是用户一直强制刷新页面,请不会去请求服务器了,这样就避免了不必要的访问,一定程度上缓解了服务器压力。