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
The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked. Imagine, for example, that your ASP.NET MVC application displays a list of database records in a view named Index.
In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action. Output caching basically allows you to store the output of a particular controller in the memory.
The output cache is located on the Web server where the request was processed. This value corresponds to the Server enumeration value. The output cache can be stored only at the origin server or at the requesting client. Proxy servers are not allowed to cache the response.
config file. By configuring output caching in the web configuration file, you can control it on one central location. You can create one cache profile and apply the profile to several controllers or controller actions. Also, you can modify the web configuration file without recompiling your application.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With