Thursday, October 19, 2006

[ASP.NET 2.0] Post-Cache Substitution

Post-Cache Substitution, a new feature that is not so eye-catching compared to the other new features introduced in ASP.NET 2.0 like Master Pages, Personalization, DataSource Control and etc. Basically, Post-Cache Substitution allows developers dynamically update the contents of output-cached portions (eg. header, footer). When a header user control (header.ascx) is given the following directive

<%@ OutputCache Duration=3600 VaryByParam=none %>

It tells the page to be partially cached for an hour (3600 seconds). If there is current date and time showing in the header section, it is unlikely that the time will be updated for every second since it is cached for an hour long.

There are common 2 ways of implementation of Post-Cache Substitution solves this problem for you - Use of Substitution Control and Substitution API.

1. Substitution Control
This control tells the page not to cache the section for its dynamic contents. Every contents in the control would not be cached.

1. To use this control, drag the Substitution Control from VS 2005's ToolBox and drop it onto your WebForm.

2. The control has a MethodName property, which is assigned to a static method. In the code-behind, define a static method that accepting a page context as parameter.

public static string GetCurrentDateTime(HttpContext context)
return DateTime.Now.ToLongTimeString ();

3. Back to Design View. In the control's property window, assign GetCurrentDateTime to MethodName property. This ascertains that subsequent requests to the page call the method again to generate dynamic content.

2. Substitution API
This implementation uses the in-lline code, by calling the Response.WriteSubstitution() method that accepting name of method as parameter. Thus, in your ASPX HTML view, add this

<% Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentTime)); %>

It would change client-side cacheability to server cacheability, which the dynamic contents are not cached on clients.

No comments: