If you want to know what is reCAPTCHA and how to use it in your ASP.NET Web application then please refer to the Tip “How to use reCAPTCHA in your site?”
In the above Tip i am validating the captcha on postback. But this tip will show you how to validate the captcha by AJAX without any postback.
For that reason you require a reCAPTCHA control in your page and on click of any button we will validate the captcha. In the background we will make an Ajax call to the server and validate the captcha. The whole approach is explained below:
STEP 1:
We have to write javascript which will make an ajax call. The javascript code for that is:
var captchaInfo = { challengeValue: Recaptcha.get_challenge(), responseValue: Recaptcha.get_response(), }); $.ajax ({ type: 'POST', url: '', data: JSON.stringify(captchaInfo), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(msg) { alert(msg.d); // Either true o false, true indicates CAPTCHA is validated successfully. } });
STEP 2:
We have to the web service which will catch the Ajax call and validate the captcha, the C# code for that is:
[WebMethod] public static bool ValidateCaptcha(string challengeValue, string responseValue) { Recaptcha.RecaptchaValidator captchaValidtor = new Recaptcha.RecaptchaValidator { PrivateKey = Convert.ToString(ConfigurationManager.AppSettings["PrivateKey"]), // Get Private key of the CAPTCHA from Web.config file. RemoteIP = HttpContext.Current.Request.UserHostAddress, Challenge = challengeValue, Response = responseValue }; Recaptcha.RecaptchaResponse recaptchaResponse = captchaValidtor.Validate(); // Send data about captcha validation to reCAPTCHA site. return recaptchaResponse.IsValid; // Get boolean value about Captcha success / failure. }