在 ASP.NET (WebHandler) 中使用 Response.Flush() 期望逐行即時輸出,卻發現瀏覽器一次性顯示所有內容。主因在於瀏覽器緩衝與HTTP 壓縮。
<div style="display:none"> + 256 字元)或改用現代瀏覽器(Chrome/Firefox/Edge Chromium)。web.config 關閉該路徑壓縮:
<system.webServer>
<urlCompression doDynamicCompression="false" />
</system.webServer>
Response.BufferOutput = true(預設),並搭配 Response.Flush()。proxy_buffering off;。public class Responseflush : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "text/html; charset=utf-8";
context.Response.BufferOutput = true;
// 觸發瀏覽器開始渲染
context.Response.Write("<div style='display:none'>" + new string(' ', 300) + "</div>");
context.Response.Flush();
for (int i = 0; i < 20; i++) {
System.Threading.Thread.Sleep(500);
context.Response.Write("第" + i + "步執行完成!<br/>");
context.Response.Flush();
}
}
public bool IsReusable { get { return false; } }
}
若仍無效,請檢查 IIS 壓縮設定與瀏覽器開發者工具 Network 面板的 Content-Encoding 與 Transfer-Encoding。