2011-12-03 41 views

回答

2

這取決於。如果是一個孩子的動作緩存存儲在MemoryCache並清除它是無證的唯一途徑,涉及破壞整個內存緩存:

OutputCacheAttribute.ChildActionCache = new MemoryCache("NewDefault"); 

當然缺點是,這種刪除所有的孩子動作和而不僅僅是這個子動作的緩存輸出。如果這是一個正常的操作,那麼你可以使用Response.RemoveOutputCacheItem方法,通過傳遞緩存的操作的url。你也可能會發現following article有趣。

緩存在ASP.NET MVC 3仍具有很長的路要走。希望他們在ASP.NET MVC 4中改進了很多東西並簡化了它。

+0

謝謝,我得看看那篇文章。 – Jonas

0

是的,這是可能的 我已經找到了答案this book。 見14.3輸出緩存在ASP.NET MVC 頁372 - 從確定性地緩存

刪除項目當我們裝飾與OutputCacheAttribute,的OutputCache 存儲其結果到ASP.NET緩存中的作用,並自動恢復它 時它必須爲後續的類似請求提供服務。如果我們知道該頁面屬於哪個緩存鍵,我們可以輕鬆地將其刪除。 不幸的是,這並不容易,即使它是,我們 不應該知道它,因爲它駐留在緩存基礎結構的內部邏輯 ,並可能在未來版本 更改,恕不另行通知。但是,我們可以做的是利用緩存 依賴關係機制來實現類似的結果。此功能類似於 ,與我們將在第 14.4節中討論的更改監視器類似。利用緩存依賴關係包括將一個緩存條目綁定到另一個緩存條目,以便在後者失效時自動刪除第一個緩存條目。

和一塊代碼

public class DependencyOutputCacheAttribute : OutputCacheAttribute 
{ 
public string ParameterName { get; set; } 
public string BasePrefix { get; set; } 

public override void OnResultExecuting(ResultExecutingContext filterContext) 
{ 
    base.OnResultExecuting(filterContext); 

    string key = string.IsNullOrEmpty(BasePrefix) 
       ? filterContext.RouteData.Values["action"] + "_" + filterContext.RouteData.Values["controller"] 
       : BasePrefix; 

    key = AddToCache(filterContext, key, ParameterName); 
} 

private string AddToCache(ResultExecutingContext filterContext, string key, string parameter) 
{ 
    if (!string.IsNullOrEmpty(parameter) && filterContext.RouteData.Values[parameter] != null) { 
    key += "/" + filterContext.RouteData.Values[parameter]; 
    filterContext.HttpContext.Cache.AddBig(key, key); 
    filterContext.HttpContext.Response.AddCacheItemDependency(key); 
    } 
    return key; 
} 
} 

和刪除緩存依賴性屬性

public class RemoveCachedAttribute : ActionFilterAttribute 
{ 
public string ParameterName { get; set; } 
public string BasePrefix { get; set; } 
public override void OnResultExecuting(ResultExecutingContext filterContext) 
{ 
    base.OnResultExecuting(filterContext); 
    string key = string.IsNullOrEmpty(BasePrefix) ? 
    filterContext.RouteData.Values["action"].ToString() + "_" + 
    filterContext.RouteData.Values["controller"].ToString() : BasePrefix; 
    if (!string.IsNullOrEmpty(ParameterName)) 
    key += filterContext.RouteData.Values[ParameterName]; 
    filterContext.HttpContext.Cache.Remove(key); 
} 
} 

最後使用它

[DependencyCache(BasePrefix = "Story", ParameterName = "id")] 
public virtual ActionResult ViewStory(int id){ 
//load story here 
} 

[HttpPost, RemoveCache(BasePrefix = "Story", ParameterName = "id")] 
public virtual ActionResult DeleteStory(int id){ 
//submit updated story version 
} 

[HttpPost, RemoveCache(BasePrefix = "Story", ParameterName = "id")] 
public virtual ActionResult EditStory(Story txt){ 
//submit updated story version 
} 

其中

public class Story { 
    int id {get;set;} //case is important 
    string storyContent{get;set;} 
} 
相關問題