2012-03-28 89 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() 
{ 
    ...