Home > ASP.NET MVC, dotnet 4, Dotnet 4.5 > Using Output Cache Profile in ASP.NET MVC

Using Output Cache Profile in ASP.NET MVC

Caching is a quintessential part of any web application, as it improves the performance and load on the web server. The simplest way to add caching to your ASP.NET MVC application is to decorate your action method with the Output Attribute as following :-

 

[OutputCache(Duration=60,VaryByParam="none")]
public ActionResult Index()
{
    var employees = db.Employees;
    return View(employees.ToList());
}

However it is not a good practice to hard code such parameter values and specially when you have to apply different values for different set of caching. For example 60 second for long, 30 seconds for medium and 10 seconds for short caching.First problem with this approach is that you have to be very careful where you are making these changes and second problem is that for some reason if you have to change these values then you have to do search and replace, which is a very bad thing and totally against the DRY ( Don’t Repeat Yourself ) principle.

So overall it is a good practice to use the output cache profile and lets see how we can declare it in our web.config file.

Web.config

<caching>
   <outputCacheSettings>
     <outputCacheProfiles>
       <add name="Long" duration="60" varyByParam="none"/>
       <add name="Medium" duration="60" varyByParam="none"/>
       <add name="Short" duration="10" varyByParam="none"/>
     </outputCacheProfiles>
   </outputCacheSettings>      
 </caching>

And here is how we use the cache profile in our action method.

[OutputCache(CacheProfile="Long")]
public ActionResult Index()
{
    var employees = db.Employees;
    return View(employees.ToList());
}

 

This is very straight forward and nothing unusual but whats the point of blogging about something which hasn’t got any gotchas. And the gotcha is that you can’t use the cache profile on a child action and MVC will through this strange exception “Duration must be positive number.”

 

The above exception is actually misleading and basically output cache profile are not supporting for child action, partial views etc,however the fix for this problem is very easy and all we have to do is just extend the OutputCacheAttribute class. So we will write our own Partial cache attribute class .

PartialCacheAttribute.cs

   1:  public class PartialCacheAttribute : OutputCacheAttribute
   2:  {
   3:      public PartialCacheAttribute(string cacheProfileName)
   4:      {
   5:          var cacheSection = (OutputCacheSettingsSection)WebConfigurationManager
   6:                              .GetSection("system.web/caching/outputCacheSettings");
   7:   
   8:          var cacheProfile = cacheSection.OutputCacheProfiles[cacheProfileName];
   9:   
  10:          Duration = cacheProfile.Duration;
  11:          VaryByParam = cacheProfile.VaryByParam;
  12:      }   
  13:  }

 

As you can see nothing special we are using the GetSection method of WebConfigurationManager class and from that section we are getting the cache profile by its name at line 8. Now our child action method is all set to be decorated with this custom attribute and this is how the action method looks like :-

[ChildActionOnly]
[PartialCache("Short")]
public string GetEmployeesCount()
{
    return db.Employees.Count().ToString();
}

 

This was an issue with MVC 3 and still it’s an issue with MVC 4, but I hope this will get fixed in in MVC 5 😉

Advertisements
  1. BD
    February 24, 2014 at 6:14 pm

    thanks! helped a lot.

  2. March 8, 2016 at 10:04 pm

    Great info. Thanks for compiling and presenting it.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: