首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 Substitution 控件與 URL 重寫:局部快取突破與地址映射新功能

     編輯:關於ASP.NET

ASP.NET 2.0 引入Substitution 控件,解決「整頁快取」與「局部即時內容」的矛盾:在啟用頁面輸出快取的頁面中,指定特定區塊不快取、每次即時產生。同時新增URL 重寫/地址映射功能,支援友善網址與舊版相容。

Substitution 控件:局部動態內容的救星

典型場景:頁面底部版權資訊、導航選單可快取 30 秒;但股票走勢圖、即時新聞必須每次重新產生。

實作範例

<%@ OutputCache Duration="30" VaryByParam="none" %>
<script runat="server" language="VB">
  Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    CachedDate.Text = DateTime.Now.ToString()
  End Sub

  Shared Function GetCurrentDate(ByVal context As HttpContext) As String
    Return DateTime.Now.ToString()
  End Function
</script>
<html><body>
  <form runat="server">
    <p>下方時間 未使用快取,每次重新整理更新:</p>
    <asp:Substitution ID="Substitution1" MethodName="GetCurrentDate" runat="server" />

    <p>下方時間 使用快取,30 秒內不變:</p>
    <asp:Label ID="CachedDateLabel" runat="server" />
    <asp:Button ID="Refresh" Text="重新整理頁面" runat="server" />
  </form>
</body></html>

Substitution 控件執行結果

圖示:Substitution 控件執行結果,上方時間即時更新,下方時間快取 30 秒

關鍵點

  • MethodName 指定 static/shared 方法,簽名為 String MethodName(HttpContext context)。
  • 方法在快取頁面輸出時被呼叫,結果直接寫入回應流,不經頁面生命週期。
  • 適用於小區塊高頻動態內容(廣告輪播、即時計數器、個人化問候)。

URL 重寫 / 地址映射

ASP.NET 2.0 內建 HttpContext.RewritePath 與 web.config <urlMappings> 區段,支援:

  • 友善網址:/Products/Books/ASP.NET → /ProductList.aspx?Category=Books&Keyword=ASP.NET
  • 舊版網址轉向:/OldPage.asp → /NewPage.aspx
  • 無副檔名網址:/About → /About.aspx
<system.web>
  <urlMappings enabled="true">
    <add url="~/Products/Books/ASP.NET" mappedUrl="~/ProductList.aspx?Category=Books&Keyword=ASP.NET" />
    <add url="~/OldPage.asp" mappedUrl="~/NewPage.aspx" />
  </urlMappings>
</system.web>

Substitution 控件與 URL 映射,是 ASP.NET 2.0 在效能與架構靈活性上的兩大實用增強。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved