Output cache per User

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.

Leave a Comment