ASP.NET Tutorial/Cache/Page Output Cache

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Creating Page Output Cache Profiles

Configure Page Output Caching in a web configuration file and apply the settings to multiple pages. 
You can set the same caching properties in a Cache Profile as you can set in an individual page"s <%@ OutputCache %> directive. 
A Cache Profile named Cache1Hour that caches a page for one hour.
File: Web.Config
<configuration>
  <system.web>
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="Cache1Hour" duration="3600" varyByParam="none" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
  </system.web>
</configuration>

File: Default.aspx
<%@ Page Language="C#" %>
<%@ OutputCache CacheProfile="Cache1Hour" %>
<!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 id="Head1" runat="server">
    <title>Output Cache Profile</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <%= DateTime.Now.ToString("T") %>
    </div>
    </form>
</body>
</html>


Manipulating the Page Output Cache Programmatically

HttpCachePolicy class can perform all the tasks that you can perform with the <%@ OutputCache %> directive. 
The page is cached on the browser, proxy servers, and web server for 15 seconds.
File: Default.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load()
    {
        Response.Cache.SetCacheability(HttpCacheability.Public);
        Response.Cache.SetExpires(DateTime.Now.AddSeconds(15));
        Response.Cache.SetMaxAge(TimeSpan.FromSeconds(15));
        Response.Cache.SetValidUntilExpires(true);
        Response.Cache.SetLastModified(DateTime.Now);
        Response.Cache.SetOmitVaryStar(true);
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Program OutputCache</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <%= DateTime.Now.ToString("T") %>
    <br /><br />
    <a href="Default.aspx">Request this Page</a>
    </div>
    </form>
</body>
</html>


OutputCache Duration="20" VaryByParam="None"

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="OutputCaching" %>
<%@ OutputCache Duration="20" VaryByParam="None" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblDate" runat="server" EnableViewState="False" Font-Bold="True" Font-Size="X-Large"></asp:Label>
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class OutputCaching : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblDate.Text = "The time is now:<br />";
        lblDate.Text += DateTime.Now.ToString();
    }
}


Varying the Output Cache by a Custom Function

You create the custom function in the Global.asax file by overriding the GetVaryByCustomString() method. 
File: Global.asax
<%@ Application Language="C#" %>
<script runat="server">
    public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if (String.rupare(custom, "css") == 0)
        {
            return Request.Browser.SupportsCss.ToString();
        }
        return base.GetVaryByCustomString(context, custom);
    }
</script>
            
File: Default.aspx
<%@ Page Language="C#" %>
<%@ OutputCache Duration="3600" VaryByParam="none" VaryByCustom="css" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load()
    {
        if (Request.Browser.SupportsCss)
            pnlCss.Visible = true;
        else
            pnlNotCss.Visible = true;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Vary By Custom</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Panel
        id="pnlCss"
        Visible="false"
        Runat="server">
        <span style="font-weight:bold">Hello!</span>
    </asp:Panel>
    <asp:Panel
        id="pnlNotCss"
        Visible="false"
        Runat="server">
        <b>Hello!</b>
    </asp:Panel>
    </div>
    </form>
</body>
</html>


Varying the Output Cache by Browser

<%@ Page Language="C#" %>
<%@ OutputCache Duration="3600" VaryByParam="none" VaryByCustom="browser" %>
<!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 id="Head1" runat="server">
    <title>Vary By Browser</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <%= DateTime.Now.ToString("T") %>
    <hr />
    <%= Request.UserAgent %>
    </div>
    </form>
</body>
</html>


Varying the Output Cache by Control

File: MasterDetails.aspx
<%@ Page Language="C#" %>
<%@ OutputCache Duration="3600" VaryByControl="dropCategories" %>
<!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 id="Head1" runat="server">
    <title>Master/Details</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <%= DateTime.Now.ToString("T") %>
    <hr />
    <asp:DropDownList
        id="dropCategories"
        DataSourceID="srcCategories"
        DataTextField="Name"
        DataValueField="Id"
        Runat="server" />
    <asp:Button
        id="btnSelect"
        Text="Select"
        Runat="server" />
    <br /><br />
    <asp:GridView
        id="grdProducts"
        DataSourceID="srcProducts"
        GridLines="none"
        Runat="server" />
    <asp:SqlDataSource
        id="srcCategories"
        ConnectionString="<%$ ConnectionStrings:Products %>"
        SelectCommand="SELECT Id,Name FROM ProductCategories"
        Runat="server" />
    <asp:SqlDataSource
        id="srcProducts"
        ConnectionString="<%$ ConnectionStrings:Products %>"
        SelectCommand="SELECT Title,Director FROM Products
            WHERE CategoryId=@CategoryId"
        Runat="server">
        <SelectParameters>
        <asp:ControlParameter
            Name="CategoryId"
            ControlID="dropCategories" />
        </SelectParameters>
    </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>


Varying the Output Cache by Header

Use the VaryByHeader to create new cached versions of a page in case of new browser header changes. 
Several standard browser headers are transmitted with each page request, including
Accept-Language: a list of languages.
User-Agent:      type of device making the request.
Cookie:          the browser cookies created in the current domain.
<%@ Page Language="C#" %>
<%@ OutputCache Duration="3600" VaryByParam="none" VaryByHeader="User-Agent" %>
<!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 id="Head1" runat="server">
    <title>Vary By Header</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <%= DateTime.Now.ToString("T") %>
    <hr />
    <%= Request.UserAgent %>
    </div>
    </form>
</body>
</html>


Varying the Output Cache by Parameter

The VaryByParam attribute causes a new instance of a page to be cached when a different parameter is passed to the page. 
File: Master.aspx
<%@ Page Language="C#" %>
<!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 id="Head1" runat="server">
    <title>Master</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView
        id="grdProducts"
        DataSourceID="srcProducts"
        AutoGenerateColumns="false"
        ShowHeader="false"
        GridLines="none"
        Runat="server">
        <Columns>
        <asp:HyperLinkField
            DataTextField="Title"
            DataNavigateUrlFields="Id"
            DataNavigateUrlFormatString="~/Details.aspx?id={0}" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource
        id="srcProducts"
        ConnectionString="<%$ ConnectionStrings:Products %>"
        SelectCommand="SELECT Id,Title FROM Products"
        Runat="server" />
    </div>
    </form>
</body>
</html>
File: Details.aspx
<%@ Page Language="C#" %>
<%@ OutputCache Duration="3600" 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 id="Head1" runat="server">
    <title>Details</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <%= DateTime.Now.ToString("T") %>
    <hr />
    <asp:DetailsView
        id="dtlProduct"
        DataSourceID="srcProducts"
        Runat="server" />
    <asp:SqlDataSource
        id="srcProducts"
        ConnectionString="<%$ ConnectionStrings:Products %>"
        SelectCommand="SELECT * FROM Products
            WHERE Id=@Id"
        Runat="server">
        <SelectParameters>
            <asp:QueryStringParameter
                Name="Id"
                Type="int32"
                QueryStringField="Id" />
        </SelectParameters>
    </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>
You can assign two special values to the VaryByParam attribute:
none: causes any query string or form parameters to be ignored. 
      
*:    caches a new cached version whenever there is a change in query string or form parameter passed to the page.
You can assign a semicolon-delimited list of parameters to the VaryByParam attribute.


You enable Page Output Caching by adding an <%@ OutputCache %> directive to a page.

The following page caches its contents for 15 seconds.
<%@ Page Language="C#" %>
<%@ OutputCache Duration="15" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load()
    {
        lblTime.Text = DateTime.Now.ToString("T");
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Cache Page Output</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label
        id="lblTime"
        Runat="server" />
    </div>
    </form>
</body>
</html>