萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 防止頁面重新整理重複提交:基於時間戳記的 BasePage 實作

問題本質

瀏覽器重新整理 (F5) 會重送最後一次 POST 要求,導致重複下單、重複寫入資料庫。傳統 Response.Redirect (PRG 模式) 雖有效但增加頁面跳轉,且使用者仍可「上一頁 → 重新整理」繞過防禦。

解決方案:繼承 Page 類別建立 BasePage

核心邏輯:初次載入寫入 Session 時間戳 → 複寫到 HiddenField → PostBack 時比對 HiddenField 與 Session 是否一致。重新整理時瀏覽器快取舊 HiddenField,造成不一致,判定為 Refresh。

完整 BasePage 代碼

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();
    }
}

專案層級自動套用 (web.config)

<configuration>
  <system.web>
    <pages pageBaseType="MyNamespace.BasePage" />
  </system.web>
</configuration>

設定後,所有新增 Web Form 自動繼承 BasePage,無需逐頁修改。

進階考量

  • 多標籤頁:同一 Session 下不同分頁共用戳記,切換分頁提交會被誤判 Refresh。解法:戳記加入 Guid 區分分頁,或改用 ViewState 儲存戳記(需啟用 ViewStateMac)。
  • 無狀態架構:叢集/負載平衡環境需將 Session 改為 Redis/資料庫模式,確保戳記跨伺服器共享。
  • API/前後端分離:改用 Idempotency Key(客戶端產生 UUID 放 Header),伺服端以 Redis SetNX 判斷冪等性。

參考資源

  • Dino Esposito - Build Your ASP.NET Pages on a Richer Bedrock
  • MSDN - Preventing Duplicate Record Insertion on Page Refresh
copyright © 萬盛學電腦網 all rights reserved