Scenario

 

By default, when we request an ASP.NET website, every request is processed by many stages, such as Page initialization, Load, Rendering, etc. This consumes many resources on server. Considering follow scenario: Many customers will browse an ASP.NET website for News page and the News page won’t be changed for several hours. Basing on common route, when multiple customers request same News page in almost same time, ASP.NET will execute the same code to generate response with same News for many times. I think you will have a feeling that the resource is wasting. Hence, someone might ask whether we can only generate response one time and serve customers with it. The answer is Cache.

 

Resolution

 

ASP.NET provides a couple of caching: Output Cache (including Page level cache and User Control level cache) and Cache API. In this article, we will discuss the Output Cache. The Output Cache has the advantage of being simple to implement, and be sufficient in many cases. It simply keeps a copy of response that was sent to client in memory and subsequent requests are then sent the cached output until the cache expires, which incredibly improve ASP.NET web application performance.

 

For ASP.NET Output Cache, ASP.NET uses @ OutputCache to declare many attributes to control the output caching policies of an ASP.NET page or a user control contained in a page.

 

<%@ OutputCache Duration="#ofseconds"

   Location="Any | Client | Downstream | Server | None |

     ServerAndClient "

   Shared="True | False"

   VaryByControl="controlname"

   VaryByCustom="browser | customstring"

   VaryByHeader="headers"

   VaryByParam="parametername"

   VaryByContentEncoding="encodings"

   CacheProfile="cache profile name | ''"

   NoStore="true | false"

   SqlDependency="database/table name pair | CommandNotification"

%>  

 

In this article, we will cover the @OutputCache's Duration, VaryByCustom, VaryByParam, VaryByControl attributes to cache output of page. For others, you can refer to http://msdn.microsoft.com/en-us/library/hdxfb6cy.aspx

 

Duration: The attribute is the time, indicates how long (in seconds) the page will be cached.

 

VaryByCustom:  Any text that represents custom output caching requirements. If this attribute is given a value of browser, the cache is varied by browser name and major version information. If a custom string is entered, you must override the GetVaryByCustomString method in your application's Global.asax file.

 

VaryByControl:  The attribute is representing the ID property values of ASP.NET server controls, which is used to vary output cache.

 

VaryByParam:  The string is used to vary the output cache. By default, these strings correspond to a query string.

 

Location:  The attribute is one of the OutputCacheLocation enumeration values (such as Web server, proxy server or browser) which indicate where page is cached. The default is Any.

 

Note: The Duration attribute is required. Either VaryByControl attribute or the VaryByParam attribute is required when you use the @ OutputCache directive on ASP.NET pages and user controls.

 

Demo

The below walkthrough demonstrates step-by-step how to use them. In the demo, we use datetime to determine whether page is cached (In the PageLoad event, we write datetime in Label control named “lblResult”.).

 

1.       Demonstrate the Duration attribute

 

#. Add @OutputCache in .aspx markup and specify the expiration time.

      In this case, we assign 10s for it. For example:

      <%@ OutputCache Duration="10" VaryByParam="none" %>

    #. Run ASP.NET web application and launch this page, and we will see that

      the datetime on page won't changed 10s when page is reloading.

  

   The markup segment: 

<%@ OutputCache Duration="10" VaryByParam="none" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>OutPutCacheWithDuration</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Label ID="lblResult" runat="server"></asp:Label>

        <br />

        <br />

        <asp:Button ID="btnPostBack" runat="server" Text="Post Back"  />

        <p>

            The page will be cached 10s, and then you can click Button to update datetime.

        </p>

    </div>

    </form>

</body>

</html>

 

2.       Demonstrate the VaryByControl attribute

 

    #. Drag and drop DropDownList in page and add three items to it.

#. Add @OutputCache in .aspx markup and specify the expiration time and VaryByControl

  attribute. For example:

      <%@ OutputCache Duration="1000" VaryByControl="ddlOption" %>

#. Run ASP.NET web application and launch this page, we can see that different item has

  corresponding cache.

 

The markup segment:

<%@ OutputCache Duration="1000" VaryByControl="ddlOption" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>OutPutCacheWithVaryByControl</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Label ID="lblResult" runat="server"></asp:Label>

        <br />

        <br />

        <asp:DropDownList ID="ddlOption" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlOption_SelectedIndexChanged">

            <asp:ListItem Selected="True">Option One</asp:ListItem>

            <asp:ListItem>Option Two</asp:ListItem>

            <asp:ListItem>Option Three</asp:ListItem>

        </asp:DropDownList>

        <p>

            The page will be rendered from cache basing on the selected item of DropDownList.

            The different item has corresponding cache.

        </p>

    </div>

    </form>

</body>

</html>

 

3.       Demonstrate the VaryByCustom attribute

 

    #. Add @OutputCache in .aspx markup and specify the expiration time

      and VaryByControl attribute with "browser" value. For example:

     <%@OutputCache Duration="1000"VaryByCustom="browser"VaryByParam="none"%>

    #. Run ASP.NET web application and launch this page with IE and FireFox

     (or browser with different name, major version ), and we will see that there is different

     cache version for different browser.

 

The markup segment:

<%@ OutputCache Duration="1000" VaryByCustom="browser" VaryByParam="none" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>OutPutCacheWithVaryByCustom</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Label ID="lblResult" runat="server"></asp:Label>

        <br />

        <br />

        <asp:Button ID="btnPostBack" runat="server" Text="Post Back" />

        <p>

            The page will be rendered from cache basing on the version of browser, such as IE and FireFox.

        </p>

    </div>

    </form>

</body>

</html>

 

4.       Demonstrate the VaryByParam attribute

 

    #. Add @OutputCache in .aspx markup and specify the expiration time

      and VaryByParam attribute with "id" value. For example:

      <%@ OutputCache Duration="1000" VaryByParam="id" %>

    #. Run ASP.NET web application and launch this page, and we can request it

      using QueryString "id" with different value. For example:

      ~/OutputCacheWithParam.aspx?id=1

      ~/OutputCacheWithParam.aspx?id=2

 

The markup segment:

<%@ OutputCache Duration="1000" VaryByParam="id" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>OutPutCacheWithVaryByParam</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Label ID="lblResult" runat="server"></asp:Label>

        <p>

            The page will be rendered from cache until the value of QueryString named "id" is

            changed or Duration is expiration.

        </p>

    </div>

    </form>

</body>

</html>

 

 

 

 

Summary

ASP.NET Caching is used to build high-performance, scalable ASP.NET web application by storing response in memory. And on subsequent requests, the page code is not executed and the cached output is used to serve the request. In this article, we focus on ASP.NET Page Output Cache, and in next session we will cover Cache API. 

How to Get the Sample

 

For a complete demo, please refer to the sample named CSASPNETOutputCache in All-In-One Code Framework project at http://cfx.codeplex.com/.

 

Feedback


If you have any feedback or questions about the samples, please feel free to post it to the discussion board or directly send it to us. Thanks.