多次向电子邮件发送验证码会导致错误消息

时间:2017-08-14 07:32:50

标签: c# asp.net sql-server email

我使用c#和asp.net,当用户创建新帐户时会输入email和national id作为主键然后如果用户点击(VIRIFY ME)按钮,程序会将此信息存储在sql server中,并发送电子邮件msg对用户,但我的问题是,当用户点击varify me按钮时,它将打印多个(电子邮件已经存在)

   protected void Button1_Click2(object sender, EventArgs e)
{



    LabelErrorMSG.Text = "";
    String email = emailtextbox0.Text.Trim();
    String notionalID = textbox_National_ID.Text.Trim();


    try
    {
        if (notionalID != "" && email != "" && counter==1)
        {
            // insert notional ID and email into database 
            getdataobj.PageSignUpInsert(notionalID, email);

            /////////////////////////////////////////////////////////////////////
            conn.Open();

            //Generate Verification Code
            String code = getdataobj.GetRandomNumber().ToString();

            // Set Verification Code in database
            SqlCommand comm = new SqlCommand("UPDATE trained SET VerificationCode='" + code + "' where NationalID='" + notionalID + "'", conn);
            comm.ExecuteNonQuery();
            conn.Close();

            //Send Email to the user with Verification Code
            SmtpClient smtpClient = new SmtpClient();
            MailMessage mailMessage = new MailMessage("saudiasummertraining@gmail.com", email, "", "");
            mailMessage.To.Add(new MailAddress(email));
            mailMessage.Subject = "Saudia Summer Traning";
            mailMessage.Body = code;
            smtpClient.EnableSsl = true;
            smtpClient.Send(mailMessage);

            Panel1.Visible = true;
        }
        else
        {
            LabelErrorMSG.Text = "you must insert national ID and email ";
        }
     ////////////////////////////////////////////////////////////////////
    }

    catch (SqlException ex)
    {
        if (ex.Number == 2627)
        {
            if (ex.Message.Contains("UNIQUE"))
            {

                ///error msg regarding Unique key violation.
                LabelErrorMSG.Text = "The email already exist ";
            }
            if (ex.Message.Contains("PRIMARY"))
            {
                //error msg regarding Primary key violation.
                LabelErrorMSG.Text = "The national ID already exist ";
            }

        }
    }

}

2 个答案:

答案 0 :(得分:0)

如果您希望用户可以多次单击验证按钮,则必须只插入一次Emai-Address,因为您将其设置为“唯一”。 在尝试插入电子邮件之前,您可以检查是否已插入电子邮件。这应该可以防止此错误。

答案 1 :(得分:0)

如果用户在执行conn.Open()后点击“验证我”按钮,则更新过程将继续,然后conn.Close()将相应执行。

当用户点击多次验证我按钮conn.Open()将继续执行多次并将更新该过程并且不会执行 conn.Close()方法,因此会抛出异常。

解决方案是用户点击“验证我”按钮后,只有在用户验证电子邮件时才会再次启用它。

相关问题