In ASP. NET prevent the form from being submitted twice due to page refresh

  • 2021-07-16 02:15:21
  • OfStack

I have seen others' anti-refresh method before, which is to refresh the page or return to the previous step to make the page expire. Here, I introduce an alternative method, using Session to deal with it.

Implementation principle:

Since refreshing the submitted form actually submits the form that was normally submitted last time, we only need to make a flag to judge whether it is a new form or an old form last time, so we can tell whether there is a repeated submission operation.

Implementation method:

Place an Hidden field on the page. When the page is loaded for the first time, save a flag in Session, and at the same time, save this flag in Hidden on the page. When submitting a form, you can know whether the form is submitted normally or repeated submission caused by refreshing the page by judging whether the flags in Hidden and Session submitted in the form are 1. It should be noted that the flags in Session are updated after each submission of the form.

Code example: There is very little code, first on the page.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test.Web.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="text" id="tbxName" runat="server" />
    <input type="text" id="tbxPass" value="" runat="server" />
    <asp:Button ID="btnSubmit" runat="server" OnClick="Button1_Click" Text="Button" />
    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
    <input id="hiddenTest" type="hidden" value="<%= GetToken() %>" name="hiddenTestN" />
  </div>
  </form>
</body>
</html>

Notices:

1 The GetToken () function is used to get the flags stored in Session.
2 Hidden uses non-server controls, This is because I use the server control, and in the background directly get the sign of Session and assign a value to this Hidden, refresh the value of Hidden in the form submitted to the server has also changed. Guess it is a server control, the value in the form is kept synchronized. Of course, it may be that I used the wrong method, quack.

Here's the background code:


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Text;

namespace Test.Web
{

  public partial class Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      // No. 1 1 Second load, generate the 1 Initial flag 
      if (null == Session["Token"])
      {
        SetToken();
      }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      if (Request.Form.Get("hiddenTestN").Equals(GetToken()))
      {
        lblMessage.ForeColor = System.Drawing.Color.Blue;
        lblMessage.Text = " Submit the form normally ";
        SetToken();// Don't forget to update it last Session Signs in 
      }
      else
      {
        lblMessage.ForeColor = System.Drawing.Color.Red;
        lblMessage.Text = " Refresh the Submit Form ";
      }
    }
    // Get the current Session The logo preserved in the 
    public string GetToken()
    {
      if (null != Session["Token"])
      {
        return Session["Token"].ToString();
      }
      else
      {
        return string.Empty;
      }
    }
    // Generate flags and save them to Session
    private void SetToken()
    {
      Session.Add("Token", UserMd5(Session.SessionID + DateTime.Now.Ticks.ToString()));
    }
    // This function is purely to make the flag a little shorter, 1 Stacked garbled code also has a unique sense of mystery. In addition, this UserMd5 The function is found on the Internet and ready-made 
    protected string UserMd5(string str1)
    {
      string cl1 = str1;
      string pwd = "";
      MD5 md5 = MD5.Create();
      //  Encrypted is 1 An array of bytes 
      byte[] s = md5.ComputeHash(Encoding.Unicode.GetBytes(cl1));
      //  Converts an array of byte type to a string by using a loop, and this string   Is the result of regular character formatting 
      for (int i = 0; i < s.Length; i++)
      {
        //  Use the resulting string 106 Binary type format. The character after the format is   Lowercase letters, if you use uppercase ( X ), the formatted characters are uppercase characters 
        pwd = pwd + s[i].ToString("X");
      }
      return pwd;
    }
  }
}

Notices:

1 The flag should be generated when the page is loaded for the first time, and it will not be used in the future.
At the end of the function processed by the form, remember to update the flag.
I chose the current SessionID plus the current time millisecond value for the logo, which can basically avoid the duplication of the logo. After that, I carried out MD5 once, purely to make the logo shorter. Of course, it means 1 point safety, haha.
These are all the codes, which are very simple. I don't know if it is too simple or if you have a better method. I didn't find similar codes on the Internet, so I wrote them down and shared them with you. If there is a better method, I hope I can tell you, because I haven't done Web development for a long time, and I'm afraid there are many new technologies.


Related articles: