2012-03-28 32 views
6

是否有使用的OutputCache屬性來緩存結果的唯一註銷用戶並重新評估了登錄的用戶實例的方式:輸出緩存MVC3只註銷用戶緩存

我想

[OutputCache(onlycacheanon = true)] 
public ActionResult GetPhoto(id){ 
    var photo = getPhoto(id); 
    if(!photo.issecured){ 
     return photo... 
    } 
    return getPhotoOnlyIfCurrentUserHasAccess(id); 
    //otherwise return default photo so please don't cache me 
} 

回答

8

您可以使用[OutputCache]中的VaryByCustom屬性。

然後覆蓋HttpApplication.GetVaryByCustomString並檢查HttpContext.Current.User.IsAuthenticated

  • 返回"NotAuthed"或類似如果沒有認證(激活緩存)
  • Guid.NewGuid().ToString()無效緩存
+1

這是非常的事我是缺少謝謝。我沒有意識到空禁用緩存。 – maxfridbe 2012-03-28 06:08:55

+0

不知道它可用。謝謝:) – 2012-03-28 10:09:35

+0

@maxfridbe:不要忘記接受答案。 – jgauffin 2012-04-23 18:25:07

4

這是我如何實現以上。

在Global.asax.cs中:

public override string GetVaryByCustomString(HttpContext context, string custom) 
{ 
    if (custom == "UserId") 
    { 
     if (context.Request.IsAuthenticated) 
     { 
      return context.User.Identity.Name; 
     } 
     return null; 
    } 

    return base.GetVaryByCustomString(context, custom); 
} 

用法在輸出緩存屬性:

[OutputCache(Duration = 30, VaryByCustom = "UserId" ... 
public ActionResult MyController() 
{ 
    ...