How to prevent a user from resubmitting a form?

前端 未结 1 1493
天涯浪人
天涯浪人 2021-01-20 18:08

I am developping a Single Page Application.

At the end of the application, the user gets to submit his contact information (name, phone number, etc)

相关标签:
1条回答
  • 2021-01-20 18:15

    Here is a very simple example, where I use a static variable on page and avoid database.

    the asp.net page is

    <asp:Literal runat="server" ID="txtInfos"></asp:Literal><br />
    <asp:TextBox runat="server" ID="txtEmail"></asp:TextBox><br />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />/>
    

    and the code behind.

    static Dictionary<string, DateTime> cLastSubmits = new Dictionary<string, DateTime>();
    
    private static readonly object syncLock = new object();
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        DateTime cWhenLast;
    
        lock (syncLock)
        {
            var cNowIs = DateTime.UtcNow;
            if (cLastSubmits.TryGetValue(txtEmail.Text, out cWhenLast))
            {
                if (cWhenLast > cNowIs )
                {
                    txtInfos.Text = "Please contact us again after 10 seconds";
                    return;
                }
                else
                {
                    // ok I let him submit the form, but note the last date time.
                    cLastSubmits.Remove(txtEmail.Text);
                }
            }
    
            foreach(var DelMe in cLastSubmits.Where(x => cNowIs > x.Value).ToList())
                cLastSubmits.Remove(DelMe.Key);
    
            // if reach here, note the last datetime of submit            
            cLastSubmits.Add(txtEmail.Text, cNowIs.AddSeconds(10));
        }
    
        // and submit the form.
        txtInfos.Text = "thank you for submit the form";
    }
    

    Some notes.

    • If you have many pools (web garden), then this may left user to submit at the same time up to the pool you have.
    • Of course if a user submit fake data this can not protect you, and thats why we can use:

      1. The honey pot trick.
      2. captcha
      3. Other control thats understands the bots
      4. Code that understand the re-submit.
    0 讨论(0)
提交回复
热议问题