1. 程式人生 > >防止重復提交 aspx.net

防止重復提交 aspx.net

esp get 瀏覽器 提交 服務 bject 服務器 protected string

:服務器控制。
後臺生成一個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);
}
}
}
}

防止重復提交 aspx.net