Jitesh Byahut 8/12/2014 3249

Page Output Caching

Page output caching provides facility to cached the entire page content in memory and after that the page is retrieved from the cache when user request that page next time. Retrieving page from cache is faster than every time new request for a page. The page is cached in multiple locations. By default, the page is cached on the browser, any proxy servers, and on the web server.

The Page will be cached for the amount of time that you specify but when server memory resources become low, cached items are automatically evicted for the cache.

To enable Page Output Caching on page, add OutputCache directive on top of page. For example, in below example code, I cached the page by adding OutputCache directive and define cache time is 20 seconds.

For testing of cache, I added a label control that shows current date time when page is loaded. Now, run this page it will show data time but when refreshed or re-run the page it will still showing previous data time until 20 seconds have passed because your page is cached for 20 seconds.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default2" %>

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

 

<!DOCTYPE html>

 

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

<head runat="server">

    <title>Caching Concept</title>

</head>

<body>

   

    <form runat="server">

        <div>

            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>           

        </div>

    </form>

</body>

</html>

 

protected void Page_Load(object sender, EventArgs e)

{

    Label1.Text = DateTime.Now.ToLongTimeString();

}

When you cache a page, the contents of the page are not regenerated each time you request the page. The .NET class that corresponds to the page is not executed with each page request. The rendered contents of the page are cached for every user that requests the page.

The page is cached in multiple locations. By default, the page is cached on the browser, any proxy servers, and on the web server.

The page is cached for 15 seconds. You can assign a much larger number to the duration attribute. For example, if you assign the value 86400 to the duration parameter, then the page is cached for a day.

Cache by programmatically in C#

        // Define cache type

        Response.Cache.VaryByParams["None"] = true;

        // Define cache location

        Response.Cache.SetCacheability(HttpCacheability.Public);

        // Define cache expiry duration

        Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));

        // Disable web server caching

        Response.Cache.SetNoServerCaching();

        // Prevent a page to list in the browser history cache

        Response.Cache.SetAllowResponseInBrowserHistory(true);

Output Cache by Parameter

Suppose your page every time displaying different-different page contents and that depends on query string. So in this case if you cache the page VaryByParam="none" your page is displaying same page content even your query string is changed. To solve this problem use VaryByParam attribute and pass query string id as its values. Now page cached new instance of page when different parameter is passed to the page.

Below examples demonstrate that how it’s working. Here we are displaying time on the page. When page get different query string then page cached for that query string and displaying time is not changed during cache duration if that query string again passed to that page.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

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

 

<!DOCTYPE html>

 

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

<head runat="server">

    <title>VaryByParam</title>

</head>

<body>

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

    <div>       

        <asp:Label ID="Label1" runat="server"></asp:Label><br />

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

    </div>

    </form>

</body>

</html>

 

protected void Page_Load(object sender, EventArgs e)

{

    if (Request.QueryString["id"] != null)

    {

            Label1.Text = "id = " + Request.QueryString["id"].ToString();

            Label2.Text = DateTime.Now.ToLongTimeString();

    }

}

Page Output Cache by Control

There are lots of control on page that works dynamically according to their requirement and if you cached entire page then all controls are not updated till cache time. So to overcome from this type of problems, we can use cache by control instead of entire page.

Below examples demonstrate that how to use cache by control. Here we showing records in GridView on DropDownList selected index. So, we cached dropdownlist by using VaryByControl. When you select item from dropdownlist page is loaded every time and displaying time is changed to current time.

Now, select any option from dropdownlist then page is cached and when you select same option from dropdownlist then page is showing previous cached content and your time is not showing current time because it’s cached.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<%@ OutputCache Duration="60" VaryByControl="DropDownList1" %>

 

<!DOCTYPE html>

 

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

<head runat="server">

    <title>VaryByParam</title>

</head>

<body>

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

    <div>

          

        Record Retrieving  time :<asp:Label ID="Label1" runat="server"></asp:Label><br /><br />

       

        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"

           OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>

        <br /><br />

 

        <asp:GridView ID="GridView1" runat="server"></asp:GridView>

    </div>

    </form>

</body>

</html>

DataConnection db = new DataConnection();

 

    protected void Page_Load(object sender, EventArgs e)

    {       

        if (!IsPostBack)

        {

            FillDropdownlist();

        }

    }

    // Fill dropdownlist

    public void FillDropdownlist()

    {

        DataTable dt = db.GetDataTable("Select ID, Name from tbl_students");

        if (dt.Rows.Count > 0)

        {

            DropDownList1.DataSource = dt;

            DropDownList1.DataTextField = "Name";

            DropDownList1.DataValueField = "ID";

            DropDownList1.DataBind();

        }

    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

    {

        if (DropDownList1.SelectedIndex > 0)

        {

            FillGridView(DropDownList1.SelectedValue);

        }

    }

    // GridView fill method

    // db.GetDataTable is function which return DataTable according to passed sql query

 public void FillGridView(string id)

  {

    Label1.Text = DateTime.Now.ToString();

 

    DataTable dt = db.GetDataTable("Select ID, Name, Branch, City from tbl_students where ID=" + id);

    if (dt.Rows.Count > 0)

    {

         GridView1.DataSource = dt;

         GridView1.DataBind();

    }

 }

Specify cache location

When we use Page Output Caching then page is cached in three locations: web server, proxy server and browser. By default location is web server.

You can set cache location according to your requirement. To set cache location, Page OutputCache directive provides an attribute named Location which is specifying cache location.

In above image, you can see that visual studio intelligence showing location options. In below table, we explaining about those location options.

Options Description
Any The page is cached on the browser, proxy servers, and web server (the default value).
Client The page is cached only on the browser.
Downstream The page is cached on the browser and any proxy servers but not the web server.
None The page is not cached.
Server The page is cached on the web server but not the browser or any proxy servers.
ServerAndClient The page is cached on the browser and web server, but not on any proxy servers.

Create Page Output Cache Profiles in Web.config

Instead of configuring Page Output Caching for each page in an application, you can configure Page Output Caching in a web configuration file and apply the settings to multiple pages. You can create a Cache Profile. Creating Cache Profiles makes your website easier to manage.

<caching>

      <outputCacheSettings>

        <outputCacheProfiles>

          <add name="cache1" duration="30" varyByParam="none"/>

          <add name="cache2" duration="60" varyByParam="id"/>

          <add name="cache3" duration="20" location="Client"/>

        </outputCacheProfiles>

      </outputCacheSettings>

</caching>

In above code, we define cache profiles contains the definition for a Cache Profile named cache1 that caches a page for one hour.

Uses the cache1 profile. This profile is set with the <%@ OutputCache %> directive’s CacheProfile attribute.

<%@ OutputCache CacheProfile="cache1" %>

Disable cache in application

You can disable cache from Web.Config that reflected in all application.

<caching>

      <!--To disable output cache form application-->

      <outputCache enableOutputCache="false"/>     

</caching>


Please give your feedback for improving this page