2012年12月19日 星期三

清除 OutputCache 的方法

繼上篇在套用 Master Page 下使用 OutputCache後,這篇就來寫一下如何清 OutputCache。

清除單頁 OutputCache 的方式可使用下列語法

HttpResponse.RemoveOutputCacheItem("/test.aspx");

參考來源: http://www.dotblogs.com.tw/ajun/archive/2008/02/18/1078.aspx 


但如果想要清除所有的 OutputCache,上網找到一個方法,實際測試是可以 WORK 的,以下為sample。

Global.asax
<%@ Application Language="C#" %>


Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache Location="Server"  VaryByParam="*" Duration="60" %>
.
.
.

    
. . .
Default.aspx.cs
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.AddCacheItemDependency("task-index");

        lblNow.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
    }
ClearOutputCache.aspx
.
.
.

.
.
.
ClearOutputCache.aspx.cs
    protected void btnClear_Click(object sender, EventArgs e)
    {
        HttpContext.Current.Cache.Insert("task-index", DateTime.Now); 
    }
如果是使用 UserControl ,可以參考這篇 ASP.NET: clear user control output cache

註:清除 OutputCache 的功能要放在另一頁,如果要做在同一頁可以使用 AJAX 技術。

沒有留言: