Output cache per User

后端 未结 2 1547
余生分开走
余生分开走 2020-12-03 06:08

Hi have quite a memory intensive dashboard which is different per user. How do I cache the response based on the current logged in userID which is not passed as a parameter

相关标签:
2条回答
  • 2020-12-03 06:30

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

    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 will let you write a custom method to determine whether there will be a Cache hit / miss by returning a string that will be used as some sort of a 'hash' per Cache copy.

    0 讨论(0)
  • 2020-12-03 06:39

    Modify your code a bit and add a hidden field in your form that has the userId hash, when you're POSTing.

    Or a better way is to use the VaryByCustom method, and vary based on a user cookie value.

    Here is a good reference:

    http://codebetter.com/darrellnorton/2004/05/04/asp-net-varybycustom-page-output-caching/

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