Caching Pages in ASP.NET

Discussion in 'ASP.NET' started by coderzone, Apr 18, 2007.

  1. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    736
    Likes Received:
    38
    Trophy Points:
    28
    The most glaring difference between Web and stand-alone applications is the disconnected nature of the Web. That is, a Web application isn't constantly connected (to a database server, application server, etc.), and a stand-alone application is. The constant server calls by the Web application can degrade performance. One way to circumvent the server calls is through caching, which is relatively simple on ASP.NET.

    Where is the data?



    Caching is a method for storing data for a specific period of time. In a Web application, the cached data is used as opposed to making another call to the server, which positively affects performance. ASP.NET allows the developer to specify caching on a page-by-page basis, or it may be controlled programmatically. Controlling caching at the page level involves an ASP.NET page directive.

    Caching ASP.NET pages



    You can use the OutputCache page directive to cache a page and all of its data. The current state of the page is stored when it's used. This means that all contained data is stored.

    The directive contains two required attributes: Duration and VaryByParams. The Duration attribute specifies how long (in seconds) the data is cached. The VaryByParams attribute allows a page to be cached by a corresponding HTTP parameter; it also allows multiple versions of a page to be cached. (Multiple values are supported; they should be separated by semicolons.) The directive has the following syntax:

    Code:
    <%@ OutputCache Duration="300" VaryByParams="None" %>
    This example will cache the page for 300 seconds without using any parameters. The VaryByParams attribute often confuses beginning ASP.NET developers, but it's really very simple. It can be used to specify an HTTP GET or POST variable as the basis for caching; these values are submitted by HTTP forms (field values), so the VaryByParams attribute allows you to cache a page by data submitted to it. I've seen it frequently used on search pages where it allows the page to be cached according to the search term submitted, so it allows different versions of the page to be cached. The following OutputCache directive caches the corresponding page for 600 seconds (10 minutes) according to the value submitted in the SearchValue field:

    Code:
    <%@ OutputCache Duration="600" VaryByParams="SearchValue" %>
    Any different SearchValue field value results in a different cached page. Caching the entire page is a powerful option, but it may not be necessary--you may need to cache only a portion of the page. This may be accomplished with what is called fragment caching. The OutputCache attribute may be tied to an ASP.NET user control as well as an entire page. This allows only the portion of the page contained within the user control to be cached; thus only a page fragment is cached. The OutputCache direction for a user control is the same as the page syntax, so no change is necessary and the VaryByParams attribute is supported as well.

    The OutputCache directive contains three additional optional attributes that may be used in conjunction with the previous three:
    • Location: Specifies where the page is cached.
    • VaryByHeader: Allows a page to be cached based on different HTTP headers. Multiple values are supported; they should be separated by semicolons.
    • VaryByCustom: Defines custom criteria for when a page should be loaded from the cache or when it should be regenerated.
    The Location attribute has four accepted values:
    • NoCache: Forces proxy server to revalidate the request with the originating Web server.
    • Private: Specifies page is cacheable only on the client. This is the default value.
    • Public: Specifies page may be cached only by both client and proxy servers.
    • Server: Specifies page may be cached only at the originating Web server.
    The VaryByHeader attribute can be useful if varying HTTP headers are causing problems in an application. One good example is the support of different browsers; this may be used as the basis for caching by using the VaryByHeader attribute and the User-Agent HTTP variable:

    Code:
    <%@ OutputCache Duration="600" VaryByParam="none" VaryByHeader="User-Agent" %>
    This creates a cached version for each different client that requests the page. The last attribute, VaryByCustom, allows the developer to choose when requested content should be loaded from cache. This is accomplished by overriding the GetVaryByCustomString method inside Global.asax. One way I've seen this method used is for caching pages according to a user's session id. The OuputCache directive appears first:

    Code:
    <%@ OutputCache Duration="600" VaryByParam="None" VaryByCustom="SessionID" %>
    This is utilised by inserting the code in the Global.asax file. The session id is stored as a cookie, so this is used to retrieve the value for the VaryByCustom attribute. The following C# code shows how this is accomplished:

    Code:
    public override string GetVaryByCustomString (HttpContext context, string arg)
    {
    	if (arg.ToLower () == "sessionid") 
    	{
    		HttpCookie cookie = context.Request.Cookies["ASP.NET_SessionId"];
    		if (cookie != null)
    			return cookie.Value;
    	}
    	return base.GetVaryByCustomString (context, arg);
    }
    Decide what to cache

    Caching can increase user response time, but it also consumes memory so be careful not to cache too much. This article just scratches the surface of caching; the other side of the coin involves controlling caching from within your ASP.NET code (C#, VB.NET, etc.).
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice