瀏覽器重新整理 (F5) 會重送最後一次 POST 要求,導致重複下單、重複寫入資料庫。傳統 Response.Redirect (PRG 模式) 雖有效但增加頁面跳轉,且使用者仍可「上一頁 → 重新整理」繞過防禦。
核心邏輯:初次載入寫入 Session 時間戳 → 複寫到 HiddenField → PostBack 時比對 HiddenField 與 Session 是否一致。重新整理時瀏覽器快取舊 HiddenField,造成不一致,判定為 Refresh。
using System;
using System.Web;
using System.Web.UI;
public class BasePage : Page
{
private const string StampKey = "AntiRefreshStamp";
public BasePage() { PreRender += BasePage_PreRender; }
private void BasePage_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
SetStamp(); // 初次載入產生新戳記
// 每次渲染都將目前戳記寫入 HiddenField
ClientScript.RegisterHiddenField(StampKey, GetStamp());
}
private void SetStamp() => Session[StampKey] = Server.UrlEncode(DateTime.Now.ToString("yyyyMMddHHmmssfff"));
private string GetStamp() => Session[StampKey]?.ToString() ?? string.Empty;
/// true = 此次 PostBack 為重新整理導致的重複提交
protected bool IsRefresh
{
get
{
string posted = Request.Form[StampKey];
string current = GetStamp();
if (string.Equals(posted, current, StringComparison.Ordinal))
{
// 合法提交:更新戳記供下一次比對
SetStamp();
return false;
}
return true; // 重新整理或偽造請求
}
}
}
// 代碼後置
public partial class OrderPage : BasePage
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsRefresh)
{
ShowMessage("請勿重複提交,資料已處理過。");
return;
}
// 正常業務邏輯
ProcessOrder();
}
}
<configuration>
<system.web>
<pages pageBaseType="MyNamespace.BasePage" />
</system.web>
</configuration>
設定後,所有新增 Web Form 自動繼承 BasePage,無需逐頁修改。
Guid 區分分頁,或改用 ViewState 儲存戳記(需啟用 ViewStateMac)。