In this article I will explain with an example, how to validate Google reCAPTCHA V2 (version 2.0) in ASP.Net MVC Razor.
The Google reCAPTCHA V2 will be validated using the Captcha response received from Callback functions.
Get Google RECaptcha Site key and Secret key
You need to refer the following article for information on how to get Google RECaptcha Site key and Secret key.
Namespaces
You will need to import the following namespace.
Model
The following Model class consists of the three properties. The Key and Secret properties will hold the Google RECaptcha Key and Secret while the Response property will be used for storing the Response returned from Google RECaptcha API.
public class RECaptcha
{
public string Key = "<RECaptcha Site Key>";
public string Secret = "<RECaptcha Secret Key>";
public string Response { get; set; }
}
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the RECaptcha Model class object is returned to the View.
Action method for handling jQuery AJAX operation
This Action method handles the call made from the jQuery AJAX function from the View.
Note: The following Action method handles AJAX calls and hence the return type is set to JsonResult.
The Captcha response i.e. User Input received from the View is sent to the Google RECaptcha API for verification and the result is then saved in the Response property of the RECaptcha Model class object and finally the RECaptcha Model class object is returned as JSON back to the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View(new RECaptcha());
}
[HttpPost]
public JsonResult AjaxMethod(string response)
{
RECaptcha recaptcha = new RECaptcha();
string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + recaptcha.Secret + "&response=" + response;
recaptcha.Response = (new WebClient()).DownloadString(url);
return Json(recaptcha);
}
}
View
Inside the View, in the very first line the RECaptcha model class is declared as Model for the View. The View consists of an HTML DIV, an HTML HiddenField element and a Button. The Button has been assigned a jQuery click event handler and when the Button is clicked the Google RECaptcha will be validated.
Inside the OnLoadCallBack event handler of the Google RECaptcha API, the RECaptcha is rendered on the page using the render function which accepts the ID of the HTML DIV (within which the RECaptcha will be rendered), the Google RECaptcha Site key and the Callback event handler.
The Callback event is triggered when the user answers the Captcha correctly. The Callback event handler accepts the Captcha response (which is an encoded string value).
The Captcha response value is sent to the AjaxMethod Action method (discussed earlier) which then returns back the JSON object consisting the result returned back from the Google RECaptcha API.
The returned result is stored in the HiddenField element and the Validation error message is hidden if the result is Success i.e. the Captcha is answered correctly.
The Button Click event makes sure that when the Button is clicked, the HiddenField must have the Success result else user will be prompt to answer the Google RECaptcha by displaying the error message.
@model RECaptcha_MVC.Models.RECaptcha
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
.error {
color: red;
}
</style>
</head>
<body>
<div id="dvCaptcha">
</div>
<input type="hidden" id="hfCaptcha"/>
<span id="rfvCaptcha" class="error" style="display:none">Captcha validation is required.</span>
<br/>
<input type="button" id="btnSubmit" value="Submit"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer></script>
<script type="text/javascript">
var onloadCallback = function () {
grecaptcha.render('dvCaptcha', {
'sitekey': '@Model.Key',
'callback': function (response) {
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: "{response: '" + response + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var captchaResponse = jQuery.parseJSON(r.Response);
if (captchaResponse.success) {
$("#hfCaptcha").val(captchaResponse.success);
$("#rfvCaptcha").hide();
} else {
$("#hfCaptcha").val("");
$("#rfvCaptcha").show();
var error = captchaResponse["error-codes"][0];
$("#rfvCaptcha").html("RECaptcha error. " + error);
}
}
});
}
});
};
$(function () {
$("#btnSubmit").click(function () {
$("#rfvCaptcha").hide();
if ($("#hfCaptcha").val() == "") {
$("#rfvCaptcha").show();
}
});
});
</script>
</body>
</html>
Screenshots
Google RECaptcha implemented in ASP.Net MVC
RequiredFieldValidator error message when Captcha is not answered
Google RECaptcha error message shown on incorrect answer
Google RECaptcha answered correctly
Error message shown when Google RECaptcha SiteVerify API Success status is False
Downloads