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 caching per user and to expire when the request is a new day?
I have researched this and found you can extend the OutputCache
attribute to dynamically set your duration however how can I configure this per user?
Thanks in advance
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
.
Try this in web.config,
<system.web>
...........
...........
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="UserCache" duration="1440" varyByParam="UserID" enabled="true" location="Client"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>