042. asp.net使用缓存来提高母版页的访问性能

时间:2021-08-07 23:19:04

Asp.Net缓存技术是一项非常重要的技术, 当一个页面被频繁的访问, 如果不使用缓存技术, 那么每访问一次就要回发一次服务器, 显然这样对服务器造成很大的负担, 所以, 可以在被频繁访问的页面中设置缓存, 可以提高网站性能.这里介绍如何只缓存母版页而不缓存关联的内容. 因为如果在母版页中输出缓存(OutputCache)后, 所有和此母版页关联的内容页都将被缓存

内容页代码:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="无标题页" %>
<%--母版页中的内容将被缓存10秒钟--%>
<%@ OutputCache Duration="10" VaryByParam="none" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Substitution ID="Substitution1" runat="server" MethodName="GetNowTime"/>
</asp:Content>

内容页后台代码:

 public static string GetNowTime(HttpContext hc)
{
return "这是内容页中的内容 " + DateTime.Now.ToString();
}

母版页代码:

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!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>无标题页</title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblTime" runat="server"></asp:Label>
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>

母版页后台代码:

protected void Page_Load(object sender, EventArgs e)
{
lblTime.Text = "这是母版页中的内容 " + DateTime.Now.ToString();
}

最终效果:

042. asp.net使用缓存来提高母版页的访问性能