Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output cache per User

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 but needs to be derived from the current logged in user. It is my understanding VaryByParam looks at the request context

Also there is a value in the database that when this is changed the cache needs to be reset

like image 600
CR41G14 Avatar asked Jun 19 '13 09:06

CR41G14


2 Answers

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.

like image 128
haim770 Avatar answered Nov 10 '22 19:11

haim770


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/

like image 3
Tamim Al Manaseer Avatar answered Nov 10 '22 21:11

Tamim Al Manaseer