(转)更新页面缓存OutputCache

原文处处:http://www.cnblogs.com/waynechan/p/3232672.html

为什么要使用OutputCache

我认为OutputCache是最简单的缓存技术了,它针对的是页面级别的,简单的一条指令就可以达到缓存的效果,有效的减轻服务器的压力和减少带宽,对于网站一些不会频繁更新内容的页面,我们可以使用OutputCache来提供性能。



为什么要更新OutputCache

作为网站的管理者,肯定要赋予他控制网站每一个部分的能力,假如网站要更新一个内容,而OutputCache还没有失效,难道要重启站点来生效吗?这时候,一个更新OutputCache的功能就显得很有必要了。



如何更新OutputCache

一、 webForm

首先,我们看看OutputCache的效果,在Index.aspx 页面的上面添加这样一条OutputCache指令,意思为页面缓存10秒钟,并且不针对任何的参数。
<%@ OutputCache Duration="10" VaryByParam="none"%>

然后再后台Page_Load函数里,输出当前的时间

public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.ToString());
}
}


浏览器查看Index.aspx页面,输出了当前的时间,这很正常,当我们不断的按F5刷新当前页面的时候,我们会发现输出的时间并没有改变,甚至在Page_Load方法体内断点也不会进来,这证明了并没有执行后台函数,当10秒钟过去了,时间也被更新出来了。



我们现在所要想做的是,在这10秒钟的缓存期过期之前,用我们的办法来更新页面缓存。

Step1:修改指令,增加 VaryByCustom 属性
<%@ OutputCache Duration="10" VaryByParam="none" VaryByCustom="Index_Key" %>

Step2:新建一个全局应用程序文件Global.asax,并且重写GetVaryByCustomString 方法

public override string GetVaryByCustomString(HttpContext context, string custom)
{
if (custom == "Index_Key")
{
var flag = context.Cache["Index_Key"];
if (flag == null)
{
flag = DateTime.Now.Ticks;
context.Cache["Index_Key"] = flag;
}
return flag.ToString();
}
return base.GetVaryByCustomString(context, custom);
}


Step3:更新OutputCache的操作

/// <summary>
/// 更新OutputCache
/// </summary>
protected void btn_UpdateOutputCache_Click(object sender, EventArgs e)
{
HttpRuntime.Cache.Remove("Index_Key");
}


效果如下图,刷新页面,在缓存里的时间是42秒,



按照上面的例子,10秒钟内,缓存时间应该都是42秒才对的,现在我们增加了更新OutputCache的功能,点击一下,缓存里的时间被更新了,证明我们这个更新OutputCache是成功的!!





原文地址:https://www.cnblogs.com/wenghaowen/p/3243216.html