为每个用户mvc配置输出缓存

CR4*_*G14 18 c# asp.net-mvc asp.net-mvc-3

我有一个用户特定的仪表板.仪表板每天只会更改,我想使用MVC's OutputCache.有没有办法配置每个用户的缓存,并在请求是新的一天时到期?

我研究了这个,发现你可以扩展OutputCache属性来动态设置你的持续时间但是我如何配置每个用户?

提前致谢

hai*_*770 28

在你的Web.config:

<caching>
  <outputCacheSettings>
    <outputCacheProfiles>
      <add name="Dashboard" duration="86400" varyByParam="*" varyByCustom="User" location="Server" />
    </outputCacheProfiles>
  </outputCacheSettings>
</caching>
Run Code Online (Sandbox Code Playgroud)

在你的Controller/ Action:

[OutputCache(CacheProfile="Dashboard")]
public class DashboardController { ...}
Run Code Online (Sandbox Code Playgroud)

然后在你的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);
}
Run Code Online (Sandbox Code Playgroud)

实质上,GetVaryByCustomString您可以编写自定义方法来确定是否存在缓存hit/miss.