2012-03-28 15 views
6

Có cách nào để sử dụng thuộc tính OutputCache để cache các kết quả của chỉ đăng xuất khỏi người sử dụng và đánh giá lại cho người dùng đăng nhập Ví dụ:MVC3 OutputCache chỉ đăng xuất khỏi người sử dụng bộ nhớ đệm

Những gì tôi muốn

[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 
} 

Trả lời

8

Bạn có thể sử dụng thuộc tính VaryByCustom trong [OutputCache].

Sau đó ghi đè HttpApplication.GetVaryByCustomString và kiểm tra HttpContext.Current.User.IsAuthenticated.

  • Return "NotAuthed" hoặc tương tự nếu không được xác thực (kích hoạt bộ nhớ cache)
  • Guid.NewGuid().ToString() để làm mất hiệu lực bộ nhớ cache
+1

Đó là điều rất tôi nhớ da diết cảm ơn bạn. Tôi đã không nhận ra bộ nhớ đệm vô hiệu hóa null. – maxfridbe

+0

Không biết nó đã có sẵn. Cảm ơn bạn :) –

+0

@maxfridbe: Đừng quên chấp nhận câu trả lời. – jgauffin

4

Đây là cách tôi thực hiện ở trên.

Trong 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); 
} 

Cách sử dụng trong Output cache Thuộc tính:

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