如何在"联系我们"窗体中使用ASP.NET Webform实现reCaptcha v3



我不知道如何在ASP.NET(而不是MVC(中的Contact us webform中实现google Retratcha v3。请帮我把这个问题缩短一下。

在ASPX页面中,将以下代码放在<asp:Content ID="Content2" ContentPlaceholderID="maincontent" runat="server">之后的顶部

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
function popup() {
swal({
title: "Successful!",
text: "Your enquiry is submitted. Thank you for contacting us.",
icon: "success",
button: "Ok",
});
}
function popupservererror() {
swal({
title: "Server Error!",
text: "Server error ! Try again later.",
icon: "error",
button: "Ok",
});
}
function errorcaptcha() {
swal({
title: "Catcha Error!",
text: "Captch error ! Try again later.",
icon: "error",
button: "Ok",
});
}
</script>
<script src="https://www.google.com/recaptcha/api.js?render=6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT"></script> /*Site Key*/ /*6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_*/
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT', { action: 'contact_us' }).then(function (token) {
document.getElementById("<%=hf_token.ClientID%>").value = token;
});
});
</script>
<script src="http://www.google.com/recaptcha/api.js?render=6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT', { action: 'contact_us' }).then(function (token) { //6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_//
$.ajax({
type: "POST",
url: "Default.aspx/SetToken",
data: JSON.stringify({ _token: token }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log('Passed the token successfully');
},
failure: function (response) {
alert(response.d);
}
});
});
});
</script>
<script src="js/main.js"></script>

现在,请参阅下面ASPX.CS页面的代码以了解操作。

using App.BAL.Master;
using App.BAL.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
namespace Supplychain_cms.contact
{
public partial class index : System.Web.UI.Page
{
private string recaptchaSecret = "6LfYRxseAAAAAKu__YvhSPEQVJBVunOeeutWN8ro";  /*Secret Key --- 6LerAgceAAAAAM7gGAKouqHnz7w9KwrI25OnIjyw*/
private string Token = string.Empty;
private ResponseToken response = new ResponseToken();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Submit_click(object sender, EventArgs e)
{
try
{
if (CaptchaVerify().Success)
{
string to_username = ConfigurationManager.AppSettings["to_username"].ToString();
string form_username = ConfigurationManager.AppSettings["form_username"].ToString();
string form_password = ConfigurationManager.AppSettings["form_password"].ToString();
string smtpAddress = "smtppro.zoho.in";
int portNumber = 587;
bool enableSSL = true;
using (MailMessage mail = new MailMessage())
{
string template = File.ReadAllText(Server.MapPath("~/main-assets/components/contactmail.html"));
template = template.Replace("FULLNAME", txt_Name.Value);
template = template.Replace("EMAILID", txt_Email.Value);
template = template.Replace("MESSAGE", txt_Message.Value);
mail.From = new MailAddress(form_username, "Supply Chain");
mail.To.Add(to_username);
mail.Subject = "New appointment query from " + txt_Name.Value + " for SuplyChain";
mail.Body = template.ToString();
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(form_username, Encrypt.Decryptdata(form_password));
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
using (MailMessage mail = new MailMessage())
{
string template = File.ReadAllText(Server.MapPath("~/main-assets/components/contactreply.html"));
template = template.Replace("FULLNAME", txt_Name.Value);

mail.From = new MailAddress(form_username, "Supply Chain");
mail.To.Add(txt_Email.Value);
mail.Subject = "Thank you for contacting on Supply Chain";
mail.Body = template.ToString();
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(form_username, Encrypt.Decryptdata(form_password));
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}

Page.ClientScript.RegisterStartupScript(GetType(), "popup", "popup();", true);
txt_Name.Value = "";
txt_Email.Value = "";
txt_Message.Value = "";
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "popup", "errorcaptcha();", true);
txt_Name.Value = "";
txt_Email.Value = "";
txt_Message.Value = "";
}
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(GetType(), "popupservererror", "popupservererror(); console.log('" + ex.Message + "');", true);
}
}

public ResponseToken CaptchaVerify()
{
//It should only call once
if (response.score == 0)
{
Token = hf_token.Value;
var responseString = RecaptchaVerify(Token);
response = JsonConvert.DeserializeObject<ResponseToken>(responseString.Result);
}
return response;

}
private string apiAddress = "https://www.google.com/recaptcha/api/siteverify";

private async Task<string> RecaptchaVerify(string recaptchaToken)
{
string url = $"{apiAddress}?secret={recaptchaSecret}&response={recaptchaToken}";
using (HttpClient httpClient = new HttpClient())
{
try
{
string responseString = httpClient.GetStringAsync(url).Result;
return responseString;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}

public class ResponseToken
{
public DateTime challenge_ts { get; set; }
public float score { get; set; }
public List<string> ErrorCodes { get; set; }
public bool Success { get; set; }
public string hostname { get; set; }
}
}
} 

现在转到数据库连接的Web.config文件。

<connectionStrings>
<add name="CON_NAME" connectionString="Data Source=localhost; 
Initial Catalog=db_SUPPLY_CHAIN; User ID=sa; 
Password=jagannath29" providerName="System.Data.SqlClient" />
</connectionStrings>

最新更新