Section 6.4. Cache Fragments of a Page

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.

  1. Launch Visual Studio and create a new web site project. Name the project C:\ASPNET20\chap06-CacheFragments.

  2. In the default Web Form, switch to Source View and add the @OutputCache directive. You will cache the output of this page for five seconds:

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"  Inherits="Default_aspx" %> <%@ OutputCache Duration="5" VaryByParam = "none" %>

  3. Switch to the code-behind of default Web Form. In the Page_Load event, type the following code:

    Protected Sub Page_Load(ByVal sender As Object, _                         ByVal e As System.EventArgs) _                         Handles Me.Load     Response.Write("Current (cached) Time is :" & Now) End Sub

  4. The output of the Write statement will be cached for five seconds, meaning the time will be updated every five seconds. Now, add a shared function in the default Web Form that also displays the current time:

    Public Shared Function getServerTime( _        ByVal context As System.Web.HttpContext) _        As String     Return "Current Time is :" & Now.ToString End Function

    Tip: Note the parameter of the shared function. This is required for the HttpResponseSubstitutionCallback class, as you will see later.

  5. Instead of using the Response.Write( ) method to display the time returned by this function, use the new Response.WriteSubstitution( ) method. Add the lines shown in bold to the Page_Load event:

    Protected Sub Page_Load(ByVal sender As Object, _                         ByVal e As System.EventArgs) _                         Handles Me.Load     Response.Write("Current (cached) Time is :" & Now)     Response.Write("<br/>")     Response.WriteSubstitution(New _        HttpResponseSubstitutionCallback(AddressOf _        getServerTime)) End Sub

  6. The Response.WriteSubstitution( ) method basically calls the getServerTime( ) method on every request, and the output is then inserted into the cached response.

  7. Press F5 to test the application. Refresh the page regularly and you will see that the time shown on the first line is refreshed every five seconds, while the second line is refreshed on every request (see Figure 6-12).

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

ASP. NET 2.0(c) A Developer's Notebook 2005
ASP. NET 2.0(c) A Developer's Notebook 2005
Year: 2005
Pages: 104 © 2008-2017.
If you may any questions please contact us: