ASP.NET Web Pages - 核心內建物件完整參考:Page、Request、Response、Server、Session 生命週期與實戰應用
Web Pages 執行期提供豐富的內建物件,封裝 HTTP 要求/回應、伺服器工具、頁面渲染管線、狀態管理等核心功能,掌握這些物件是開發動態網站的關鍵。
Page 物件:頁面渲染管線核心
常用方法
| 方法 | 描述 |
| RenderPage(path) | 在另一頁面中渲染指定頁面內容 (如 Header、Footer) |
| RenderBody() | 版面頁中渲染內容頁主體區域 |
| RenderSection(name [, required]) | 版面頁中渲染命名內容區塊 |
| Write(obj) | 輸出物件為 HTML 編碼字串 (防 XSS) |
| WriteLiteral(obj) | 直接輸出物件不編碼 (需確信安全) |
| Href(path [, params]) | 虛擬路徑轉瀏覽器可用 URL |
關鍵屬性
| 屬性 | 描述 |
| IsPost | 目前要求是否為 POST (初始 GET 為 false) |
| Layout | 取得/設定版面配置頁面路徑 |
| Page | 頁面、版面頁、部頁間共享資料的動態物件 |
| Request | 取得 HttpRequestBase 物件 |
| Response | 取得 HttpResponseBase 物件 |
| Server | 取得 HttpServerUtilityBase 物件 |
PageData / Page 動態資料共享機制
跨頁面、版面頁、部頁共享資料的兩種存取方式:
@* 內容頁設定 *@
@{
PageData["Title"] = "產品列表";
Page.Title = "產品列表"; // 動態屬性寫法 (相同效果)
Page.MetaDescription = "最新產品資訊";
}
@* 版面頁讀取 *@
<title>@PageData["Title"] | MySite</title>
<meta name="description" content="@Page.MetaDescription" />
PageData 為字典式存取 (索引子),Page** 為動態物件屬性存取,兩者操作同一底層資料。
Request 物件:HTTP 要求完整封裝
| 索引子/屬性 | 描述 | 範例 |
| Request[key] | 合併查詢 Form、QueryString、Cookies、ServerVariables | Request["search"] |
| Request.Form[key] | POST 表單欄位 | Request.Form["email"] |
| Request.QueryString[key] | URL 查詢字串參數 | Request.QueryString["page"] |
| Request.Cookies[key] | Cookie 值 | Request.Cookies["prefs"]?.Value |
| Request.Files[key] | 上傳檔案集合 (HttpPostedFileBase) | Request.Files["avatar"] |
| Request.Url | 完整要求 URL | Request.Url.AbsoluteUri |
| Request.UserHostAddress | 用戶端 IP | Request.UserHostAddress |
| Request.Headers[key] | HTTP 標頭 | Request.Headers["User-Agent"] |
| Request.Unvalidated(key) | 略過驗證存取 (慎用,防 XSS) | Request.Unvalidated("htmlContent") |
Response 物件:HTTP 回應控制
| 方法 | 描述 | 範例 |
| Response.Redirect(url) | HTTP 302 重導向 | Response.Redirect("~/Login") |
| Response.SetStatus(code) | 設定 HTTP 狀態碼 | Response.SetStatus(404) |
| Response.AddHeader(name, value) | 新增回應標頭 | Response.AddHeader("X-Custom", "Value") |
| Response.WriteFile(path) | 輸出檔案內容 | Response.WriteFile("~/Files/report.pdf") |
| Response.WriteBinary(data, mime) | 輸出二進位資料 | Response.WriteBinary(bytes, "image/png") |
| Response.OutputCache(sec, sliding, varyByParams) | 輸出快取 | Response.OutputCache(300, true, "category") |
| Response.Cookies[key] | 設定 Cookie | Response.Cookies["token"] = "abc"; .Expires = DateTime.Now.AddDays(30) |
Server 物件:伺服器端工具方法
| 方法 | 描述 | 範例 |
| Server.MapPath(virtualPath) | 虛擬路徑轉實體路徑 | Server.MapPath("~/App_Data/db.sdf") |
| Server.HtmlEncode(text) | HTML 編碼 (< → <) | Server.HtmlEncode(userInput) |
| Server.HtmlDecode(html) | HTML 解碼 | Server.HtmlDecode(storedHtml) |
| Server.UrlEncode(text) | URL 編碼 (查詢字串) | Server.UrlEncode("搜尋關鍵字") |
| Server.UrlDecode(urlText) | URL 解碼 | Server.UrlDecode(encodedStr) |
| Server.Transfer(path) | 伺服器端轉交 (URL 不變) | Server.Transfer("~/Error.cshtml") |
| Server.Execute(path) | 執行另一頁面並捕獲輸出 | var output = Server.Execute("~/Widget.cshtml") |
Session 與 Application 狀態管理
| 物件 | 生命週期 | 適用場景 | 範例 |
| Session[key] | 瀏覽器工作階段 (預設 20 分鐘閒置逾時) | 使用者購物車、偏好設定、暫存表單資料 | Session["Cart"] = cartItems; |
| Application[key] | 應用程式存續期間 (IIS 重啟重置) | 全站計數器、快取共用資料、功能開關 | Application["VisitorCount"]++; |
| Cache[key] | 依過期策略/相依性自動淘汰 | 資料庫查詢結果、計算結果、外部 API 回應 | Cache["Products"] = products, 300 秒 |
版面配置與區塊渲染實戰
內容頁 (_Layout.cshtml 為版面頁)
@{
Layout = "~/Shared/_Layout.cshtml";
Page.Title = "首頁";
}
@section HeaderContent {
<h1>歡迎光臨</h1>
}
<p>主要內容區域...</p>
@section Scripts {
<script src="~/scripts/home.js"></script>
}
版面頁 (_Layout.cshtml)
<!DOCTYPE html>
<html><head>
<title>@Page.Title | MySite</title>
@RenderSection("Scripts", required: false)
</head><body>
@RenderPage("~/Shared/_Header.cshtml")
@RenderBody()
@RenderPage("~/Shared/_Footer.cshtml")
@RenderSection("Scripts", required: false)
</body></html>
防止檔案被直接瀏覽:底線前綴慣例
檔案名稱以 _ 開頭 (如 _Layout.cshtml, _Header.cshtml, _AppStart.cshtml) 將被 ASP.NET 路由系統攔截,**禁止直接透過 URL 存取**,適用於:
- 版面配置頁面
- 部頁/部分視圖
- 全域初始化腳本
- 敏感設定檔
敏感資訊隔離:_AppStart.cshtml 最佳實務
@* ~/App_Data/_AppStart.cshtml (或根目錄 _AppStart.cshtml) *@
@{
// 資料庫連線字串 (實際建議放 Web.config connectionStrings)
// Database.ConnectionString = "...";
// Email 設定
WebMail.SmtpServer = "smtp.example.com";
WebMail.UserName = "noreply@example.com";
WebMail.Password = ConfigurationManager.AppSettings["EmailPassword"]; // 從加密設定讀取
WebMail.From = "noreply@example.com";
WebMail.EnableSsl = true;
// 第三方 API 金鑰
// 實際建議使用 Azure Key Vault / AWS Secrets Manager / 環境變數
}
生產環境**嚴禁**將密碼、API Key、連線字串硬編碼在原始碼中,請使用設定提供者、祕密管理服務或環境變數。