Adding Google reCAPTCHA widget to Form Pages of ASP.NET MVC Application For Protecting Them From Spam And Abuse.

Step 1: Get the Google reCAPTCHA widget Site key & Secret key

Go to Google reCAPTCHA Admin Page and get the Site key & Secret key for you web application (domain).

Step 2: Existing Form Page where we want to integrate Google reCAPTCHA

ContactUsSubmissionModel.cs – Contact Us Submission Model

HomeController.cs: Home Controller with Contact & Submit action methods

Contact.cshtml: View containing Contact Us Form

contactus.js: JavaScript code for handling “submit” button click.

Step 3: Adding Google reCAPTCHA widget to Form Page of ASP.NET MVC Application

Application Architecture:

Application With ReCaptcha

Contact.cshtml changes:

Add reference of https://www.google.com/recaptcha/api.js JS to Contact.cshtml.  Add recaptcha and recaptchaMessage Divs  to Contact.cshtml as shown in below code. Do, remember to replace data-sitekey value with one that you have got in Step 1. recaptchaMessage div is used to show reCAPTCHA error message in case of failure.

Google reCaptcha

Contact.cshtml changes are highlighted in the below code.

contactus.js changes:

contactus.js is modified to include reCAPTCHA client side verification logic and a ajax call to perform reCAPTCHA server side verification. Also, grecaptcha.reset() is called to reset the reCAPTCHA widget after the form submission.

contactus.js changes are highlighted in the below code.

HomeController.cs changes:

VerifyReCaptchaToken action method is added to verify reCAPTCHA  user response token on the server side. Do, remember to replace secret value with one that you have got in Step 1. 

Result:

reCaptcha In Action

That’s it….

Kapil Khandelwal

Web Developer, Blogger, Microsoft Certified Professional (MCP), DZone’s Most Valuable Blogger (MVB)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *