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

时间:2013-06-13 06:18:11

标签: c# asp.net-mvc asp.net-mvc-3

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

我已对此进行了研究,发现您可以扩展OutputCache属性以动态设置持续时间但是如何为每个用户配置?

提前致谢

2 个答案:

答案 0 :(得分:28)

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 { ...}

然后在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

答案 1 :(得分:2)

在web.config中尝试这个,

<system.web>
 ...........
 ...........
 <caching>
  <outputCacheSettings>
    <outputCacheProfiles>
      <add name="UserCache" duration="1440" varyByParam="UserID" enabled="true" location="Client"/>
    </outputCacheProfiles>
  </outputCacheSettings>
</caching>