6.4. Cache Fragments of a Page
Note: You can now cache portions of a page, instead of the entire page, and thereby speed up page updates.
In ASP.NET 1.x, you can either cache an entire page or cache fragments of the page using user controls. In ASP.NET 2.0, you can cache the output of a page while designating a portion of the page to be updated on every request.
6.4.1. How do I do that?
In this lab, you will create a page that uses fragment caching. The main page will use output caching, while a part of the page will be updated on every request.
Figure 6-12. The time displays are different: one is cached while the other is fresh
6.4.2. What about...
...saving output caching on disk?
By default, ASP.NET 2.0 saves the output caching on disk. This has the advantages of caching more information than what your memory allows you, as well as the ability to retrieved cached data when the web server undergoes a restart.
You can, however, turn off disk caching by modifying the DiskCacheable attribute in the OutputCache directive:
<%@ OutputCache Duration="120" VaryByParam="name" DiskCacheable="false" %>
To affect all the pages in an application, insert the <outputCache> element into Web.config. You can also specify the size of the disk to cache for the application.
<?xml version="1.0"?> <configuration> <system.web> <caching> <outputCache> <diskCache enabled="true" maxSizePerApp="5" /> </outputCache> </caching> </system.web> </configuration>
Is there a better way to manage cache profiles for the entire application? If you have many pages that you need to manage, it is always better to control the caching profile of all pages centrally. Instead of modifying the cache duration of each page individually, a much more efficient way would be to specify sets of caching profiles in the Web.config file.
The following entries in Web.config specify several caching profiles:
<system.web> <caching> <outputCacheSettings> <outputCacheProfiles> <add name="Cache30sec" duration="30" /> <add name="Cache5min" duration="300" /> <add name="Cache1hr" duration="3600" /> <add name="ShortTerm" duration="1800" /> <add name="LongTerm" duration="7200" /> </outputCacheProfiles> </outputCacheSettings> </caching> </system.web>
To use the policies defined in Web.config, simply set the profiles via the CacheProfile attribute:
<%@ OutputCache CacheProfile="ShortTerm" VaryByParam="name" %>
One advantage of the cache profile is that you can change the cache duration via the Web.config file without modifying the source of the page. In the previous example, if you think that the short term caching should be more than half an hour (1800 seconds), you can just change it to a larger value.
6.4.3. Where can I learn more?
To learn more about the various ways you can improve your web application by using caching, check out my article at http://www.devx.com/asp/Article/21751.