I can not do how to implement google recaptcha v3 in Contact us webform in ASP .NET(not in MVC). please help me to short out this problem.
Asked
Active
Viewed 2,880 times
-1
-
Check this one -> https://stackoverflow.com/questions/53590011/how-to-implement-recaptcha-v3-in-asp-net – AchoVasilev Jan 11 '22 at 14:42
-
Please add more details about your problem and add what you have tried till now – Sagar Patel Jan 19 '22 at 12:11
-
Please provide enough code so others can better understand or reproduce the problem. – Community Jan 19 '22 at 12:11
1 Answers
0
In the ASPX page put the following code at the top after the <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>
And now see the below code for ASPX.CS page for the actions.
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; }
}
}
}
Now go the Web.config file for Database connection.
<connectionStrings>
<add name="CON_NAME" connectionString="Data Source=localhost;
Initial Catalog=db_SUPPLY_CHAIN; User ID=sa;
Password=jagannath29" providerName="System.Data.SqlClient" />
</connectionStrings>

Peter Csala
- 17,736
- 16
- 35
- 75

Jagannath Patra
- 1
- 1
- 1
-
[You are using HttpClient wrong](https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/) – Wiktor Zychla Jan 29 '22 at 08:35
-