ASP.NET MVC > Caching

Creating output cache profile in ASP.NET MVC

How to create a profile for the output cache and use it in multiple actions?

The benefit of creating an output cache profile is to set the same setting in multiple action methods. If change is needed, changing the profile value affects all action method using this profile.

The cache profile can be created in root web.config file under system.web.


          <add name="Cache1Minute" duration="60" varyByParam="none"/>

Notice the highlighted settings. Here we have created a profile named “Cache1Minute” and set the duration as 60 seconds. The VarByParam is “None” so that the cached data will be saved only once for any parameter passed to the action method. This works same as ASP.NET Web Form OutputCache directive and VarByParam.

We can use above cache profile in this way in the action method.


 [OutputCache(CacheProfile = "Cache1Minute", Location = System.Web.UI.OutputCacheLocation.Server)]
  public string Index()
      return DateTime.Now.ToString();

Note that OutputCache attribute has CacheProfile parameter set as “Cache1Minute” and its Location is Server so the data cached by ASP.NET Framework for this method will be saved into the server. Every time this action method will be called within 60 seconds, the output of the 1st request will be served. After 60 seconds, the whole  method executes again and the fresh output is saved into the server memory again and all further request is served by server memory for next 60 seconds and so on.

 Views: 15516 | Post Order: 97

Write for us

Hosting Recommendations