How to enhance the scope of output cache
Output cache can be used to store the rendered HTML in the client system for a certain period of time. I.e. if the same page is requested within the specified time period, a previously cached copy of the page is displayed. No round trip, hence no delay in time. And this could be implemented by adding a single line of code in your aspx page.
'<%@ OutputCache Duration="Period in seconds" %>
Suppose you are displaying static content in your page that depends on a QueryString value. Here one can make use of output cache by directing to maintain different versions of the same page depending on the QueryString value. To do this, change the above line of code as follows.
'<%@ OutputCache Duration="xxx" VaryByParam="querystring" %>
This results in different copies of the same page being cached, for different query string values.
In most cases, we cannot expect web pages to contain only static content. So when the webpage require sdisplaying dynamic content, how can you enjoy the same benefits? Identify the areas of a page where only static content is displayed, create appropriate user controls for such areas and cache the user controls as before. This is known as partial caching.
Now think of a situation where you want to keep versions of a page or a user control according to some value other than the QueryString. This is where, VaryByCustom comes into the picture.
Suppose you are using a user control in your webpage which contains only static data, say a menu. Now depending on user type, one need to make some changes in displaying the menu. I.e. you want to cache different versions of the menu depending on user type. To implement this, one has to change the above line of code as follows.
'<%@ OutputCache Duration="xxx" VaryByCustom="UserType" %>
Then, override “GetVaryBtCustomString” method in Global.asax as follows,
' public override string GetVaryByCustomString(HttpContext context, string custom)
{
if (custom == "UserType"){
return string.Format(LoggedUser.UserType);
}
else
{
return base.GetVaryByCustomString(context, custom);
}
}
Here different versions of the user control – menu is cached for different user types.
Let the web server and end user enjoy the benefits of caching.
Related Posts
- No related posts found




