创建页面输出缓存文件依赖
可以在一个缓存页面和硬盘上的一个文件(或者一组文件)之间创建一个依赖。当文件修改时,缓存页面自动失效并在下次页面请求时重新生成。
<%@ Page Language="C#" %>
<%@ OutputCache Duration="9999" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_Load()
{
Response.AddFileDependency(MapPath("Movies.xml"));
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Output Cache File Dependency</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= DateTime.Now.ToString("T") %>
<hr />
<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
Runat="server" />
<asp:XmlDataSource
id="srcMovies"
DataFile="Movies.xml"
Runat="server" />
</div>
</form>
</body>
</html>
<%@ OutputCache Duration="9999" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_Load()
{
Response.AddFileDependency(MapPath("Movies.xml"));
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Output Cache File Dependency</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= DateTime.Now.ToString("T") %>
<hr />
<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
Runat="server" />
<asp:XmlDataSource
id="srcMovies"
DataFile="Movies.xml"
Runat="server" />
</div>
</form>
</body>
</html>
上面代码显示了当前时间,注意,时间直到Movies.xml文件被修改时才会变化。代码中使用了 Response.AddFileDependency()方法在缓存页面和磁盘上的单个文件间建立了依赖。如果需要依赖多个文件,则需要使用AddFileDependencies()代替。
使用编程的方式设置页面输出缓存过期
可以使用Response.RemoveOutputCacheItem()方法,以编程的方法,从缓存中移除一个页面。例如我们前台产品页面被缓存了,当在后台添加新的产品时就可以使用编程方式移除前台缓存的产品页面。
protected void dtlMovie_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
HttpResponse.RemoveOutputCacheItem(Page.ResolveUrl("~/MovieList.aspx"));
Response.Redirect("~/MovieList.aspx");
}
{
HttpResponse.RemoveOutputCacheItem(Page.ResolveUrl("~/MovieList.aspx"));
Response.Redirect("~/MovieList.aspx");
}