問題背景
Web 應用中常面臨用戶惡意刷新頁面導致服務器壓力增大、數據重複提交等問題。本文提供基於 Session 和 Cookies 兩種不同機制的防刷新解決方案,可根據項目需求選擇適合的方案。
方案一:基於 Session 的防刷新機制
核心邏輯
- 利用 Session 唯一標識區分用戶
- 記錄上次訪問時間,計算時間間隔
- 間隔小於閾值時攔截請求並提示
完整實現代碼
public double time;
public const int freetime = 1; // 防刷間隔:1秒
#region 防惡意刷新
if (Session.SessionID == null)
{
Response.End();
}
else if (Session["sionid"] == null)
{
Session["sionid"] = Session.SessionID;
}
if (Session["last"] == null)
{
Session["last"] = DateTime.Now;
}
else
{
DateTime thisTime = DateTime.Now;
DateTime lastTime = DateTime.Parse(Session["last"].ToString());
if (Session.SessionID == Session["sionid"].ToString())
Session["last"] = thisTime;
TimeSpan ts = thisTime - lastTime;
time = ts.TotalMilliseconds;
if (time < freetime * 500) // 500毫秒閾值
{
warm_prompt();
}
}
#endregion
public void warm_prompt()
{
Response.Write("");
Response.Write("");
Response.Write(" | ");
Response.Write("為了保證您的訪問安全,請您 " + freetime + " 秒後點擊這裡刷新此頁面 | ");
Response.Write("
");
Response.Write("
");
Response.End();
}
方案二:基於 Cookies 的防刷新機制
核心邏輯
- 在客戶端存儲訪問頁面 URL 和時間戳
- 同一頁面重複訪問時檢查時間間隔
- 超時自動跳轉,提升用戶體驗
完整實現代碼
public double time;
public const int freetime = 2; // 防刷間隔:2秒
#region 防惡意刷新
string page = Request.Cookies["page"]?.Value ?? "";
string strThisPage = HttpContext.Current.Request.Url.PathAndQuery;
DateTime LastTime = DateTime.Now;
if (page.Equals(strThisPage)) // 同一頁面重複訪問
{
TimeSpan ts = LastTime - DateTime.Parse(HttpContext.Current.Request.Cookies["time"].Value);
time = ts.Seconds;
if (time < freetime)
{
warm_prompt();
}
}
else
{
// 更新 Cookie 記錄
Response.Cookies["page"].Value = strThisPage;
Response.Cookies["time"].Value = LastTime.ToString();
}
#endregion
public void warm_prompt()
{
Response.Write("");
Response.Write("");
Response.Write(" | ");
Response.Write("為了保證您的訪問安全,頁面將在2秒後將自動跳轉到您要訪問的內容! | ");
Response.Write("
");
Response.Write("
");
Response.Write("
");
Response.End();
}
兩種方案對比與選擇建議
| 維度 | Session 方案 | Cookies 方案 |
| 存儲位置 | 服務器內存 | 客戶端瀏覽器 |
| 安全性 | 高(用戶不可篡改) | 中(可被清除/禁用) |
| 性能影響 | 增加服務器內存佔用 | 無服務器壓力 |
| 適用場景 | 高安全性需求、會話級控制 | 輕量級應用、跨會話持久化 |
進階優化建議
- 分佈式環境:Session 方案需配合 Redis 等共享存儲
- 靜態資源排除:在全局過濾器中排除 CSS/JS/圖片請求
- IP 級限流:結合 IP 地址實現更精準的防刷策略
- 友好提示:使用 AJAX 返回 JSON,前端彈窗提示而非直接輸出 HTML
根據項目架構和業務需求選擇合適方案,並結合上述優化建議,可有效構建穩健的防惡意刷新機制。