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

ASP.NET Response 物件核心方法完整參考

     編輯:關於ASP.NET

Response 物件負責將伺服器端處理結果輸出至用戶端瀏覽器,本文整理其核心方法與常用屬性,附帶實用範例。

方法總覽

方法功能
Write輸出字串/變數至瀏覽器
WriteFile直接輸出檔案內容
Redirect導向至指定 URL
Flush立即發送緩衝區內容
End停止頁面處理,返回已產生內容
Close關閉用戶端連線
Clear清除緩衝區內容
ClearHeaders清除回應標頭
BinaryWrite輸出二進位資料(圖片、檔案下載)
AppendToLog寫入自訂資料至 IIS 日誌

核心方法詳解

Response.Write

Response.Write("Hello " + userName);           // 輸出字串
Response.Write(DateTime.Now.ToString());       // 輸出變數
// 簡寫形式
<%= "Hello " + userName %>

Response.Redirect

Response.Redirect("~/Login.aspx");             // 相對路徑
Response.Redirect("https://example.com");      // 絕對 URL
// 導向並結束處理
Response.Redirect("Error.aspx", true);

Response.End

// 告知瀏覽器資料傳輸完成,IIS 停止解析後續程式碼
Response.Write("處理完成");
Response.End();

Response.BinaryWrite - 檔案下載範例

byte[] fileBytes = File.ReadAllBytes(Server.MapPath("~/Files/report.pdf"));
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=report.pdf");
Response.BinaryWrite(fileBytes);
Response.End();

Response.Flush - 長時間處理漸進輸出

for (int i = 0; i < 100; i++)
{
    Response.Write($"處理項目 {i}...<br>");
    Response.Flush();  // 立即推送至瀏覽器
    System.Threading.Thread.Sleep(100);
}

HTTP 標頭操作

Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetExpires(DateTime.Now.AddHours(1));
Response.AppendHeader("X-Custom-Header", "Value");
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved