Monday, March 21, 2011

Cache a page conditonally

Cache a page conditonally


Cache is one of the ways to improve site performance, one most used caching policy is page level cache. In .NET, we will use below directive in the page to cache the whole page(10 minutes as example).
<%@ OutputCache VaryByParam="none" Duration="600" %>
But many times we find cases that we do not want cache the entire page, but part of the page, this can be done by including the caching part of content in a user control and set OutPutCache at control level. What happens if we can not include those content in a user control or user controls? Or we want to cache multiple version of the page based on different status? For example, we have a banner with sign in/out section, based on the sign in status, we need to display the corresponding banner, however, the rest part of the page is mostly static or not frequently updated. In this case, what we can do is adding VaryByCustom, so that we can control how many versions of caching the page has. Below is the sample code.
1, Change the OutputCache directive to <%@ OutputCache VaryByParam="none" Duration="600" VaryByCustom="SignIn" %>
2, Add event handler to Global.ascx or a customized HttpModule to handle the custom status...
public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if (custom.Equals("SignIn", StringComparison.CurrentCultureIgnoreCase))
        {
            return "SignIn=" + User.Identity.IsAuthenticated.ToString();
        }
        else
        {
            return base.GetVaryByCustomString(context, custom);
        }
    }
We can apply this example to basically any status based cache or conditional cache.

Source:- http://mypath2us.com/post/2009/10/16/Cache-a-page-conditonally.aspx

No comments:

Post a Comment