[ASP.NET教程] 防止表單重復提交


第一種方法:javascript控制。缺點,一般用戶使用沒問題,但是懂點js的還是可以強行重復提交。而且,后退再提交,你也沒啥辦法。

第二種方法:服務器控制。
后台生成一個token,存入session或者其他緩存里面。渲染表單時,給form一個隱藏的token(令牌).
用戶提交表單時:
先判斷表單里面的token是否存在,不存在拒絕接受此數據;
如果存在token,判斷此表單里的token是否和session里的token一致,如果不一致,拒絕處理數據;如果一致,處理表單,並從session里移除此token.
那么,當用戶成功提交表單后,如果再次提交,會因為session里的token已刪除,從而讓服務器告訴用戶“不要重復提交表單!”.

頁面上的代碼

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
   <form id="form1" runat="server">
    <asp:HiddenField ID="HiddenField1" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="提交"/>
    <div>
        
    </div>
    </form>
</body>
</html>

 




后台代碼

using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetSession(); //首次加載的時候 給session 賦值 , 並給隱藏於  賦值,
            }
        }
        public void SetSession() 
        {
            Session["record"] = DateTime.Now.ToString();  //保存頁面上的值到session中
            HiddenField1.Value = Session["record"].ToString();  
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (HiddenField1.Value == Session["record"].ToString())  //當點擊按鈕時,他們的值一定是相等的
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "key","", true);
                //Response.Write(String.Format("<script>alert('{0}')</script>",Session["record"].ToString()));
                SetSession();    // 當執行的時候 如果是點按鈕  session 和 隱藏於的值是相等的,    要是 刷新的話, session  是肯定變得但 隱藏於的 值 是緩存 里的 上一次的 ,這是  瀏覽器的一個  bug 
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "key", "alert('請不要重復提交');", true);
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM