70-486 · C# · Certification Test · Computer programming

Output caching & caching profiles

To speed up page loading you may want to user the [OutputCache] attribute.  You must set a duration to cache the output and that value is in seconds.  So your attribute would look like

   [OutputCache(Duration = 60 )]

That’s good but what if you have data that is being paged? each page is cached which makes for a quicker load when you click the next and previous button.  What if the user edits the query string to go to a specific page?  you will get the cached data but not the rest of the UI.  To fix this we can add the following:

   [OutputCache(Duration = 60, VaryByHeader = “X-Requested-With” )]

But the page is being cached in the browser so you will need to add :

   [OutputCache(Duration = 60, VaryByHeader = “X-Requested-With”, Location = OutputCacheLocation.Server )]

You best bet is to create a separate controller action for Ajax.

Caching Profiles

So now your site is live and you are still having performance issue.  Since the site is live you really don’t want to have to change the code, recompile and then redeploy the site to increase the performance.  You also don’t want to spend a lot of time finding every place where you have done an OutputCache and tweak the duration or other parameters (I’ll just use duration for my example).  Cache profiles allow us to save the duration in the Web.config where we can make a change and see the results without recompiling and redeploying the site.  So how do we do this?  First we change the OutputCache attribute to look like this:



Then in web.config we add the following to the system.web section

      <add name=”Aggressive” duration=”300″/>

<add name=”Mild” duration=”10″/>



Scott Allen’s Building Applications with ASP.NET MVC 4

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s