Configure output cache per user mvc

后端 未结 2 1478
情书的邮戳
情书的邮戳 2020-12-23 18:07

I have a user specific dashboard. The dashboard will only change daily, I want to use MVC\'s OutputCache. Is there any way to configure the cachi

相关标签:
2条回答
  • 2020-12-23 18:13

    Try this in web.config,

    <system.web>
     ...........
     ...........
     <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="UserCache" duration="1440" varyByParam="UserID" enabled="true" location="Client"/>
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
    
    0 讨论(0)
  • In your Web.config:

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

    In your Controller/Action:

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

    Then in your 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);
    }
    

    In essence, GetVaryByCustomString lets you write a custom method to determine whether there will be a Cache hit/miss.

    0 讨论(0)
提交回复
热议问题