2013-06-19 36 views
9

你好有一個相當內存密集的儀表板,每個用戶都不同。如何根據當前登錄的用戶標識緩存響應,該用戶標識不作爲參數傳遞,但需要從當前登錄的用戶派生。這是我的理解的VaryByParam着眼於請求上下文每個用戶輸出緩存

也有是,當這個改變緩存需要重置

回答

26

在你Web.config

<caching> 
    <outputCacheSettings> 
    <outputCacheProfiles> 
     <add name="Dashboard" duration="86400" varyByParam="*" varyByCustom="User" location="Server" /> 
    </outputCacheProfiles> 
    </outputCacheSettings> 
</caching> 

在你Controller/Action

[OutputCache(CacheProfile="Dashboard")] 
public class DashboardController : Controller { ...} 

然後在您的Global.asax

//string arg filled with the value of "varyByCustom" in your web.config 
    public override string GetVaryByCustomString(HttpContext context, string arg) 
    { 
     if (arg == "User") 
     { 
      // depends on your authentication mechanism 
      return "User=" + context.User.Identity.Name; 
      //?return "User=" + context.Session.SessionID; 
     } 

     return base.GetVaryByCustomString(context, arg); 
    } 

從本質上說,GetVaryByCustomString將讓你寫一個自定義的方法來確定是否會有一個緩存hit/miss通過返回將被用來作爲某種每個緩存拷貝的「哈希」的字符串。