How to integrate Google recaptcha with ASP.Net MVC Application?

In this blog, Let’s see how can we integrate Google reCapctah with ASP.Net MVC.

What is Google ReCaptcha?

Google reCaptcha help public websites to prevent spam access on an input form like login, signup.
It is basically a way to identify that no robot is submitting the input form.

Follow below steps to integrate a Google ReCaptcha for website

  1. Search “google recaptcha” in google and click on the first link from the result.
    Click on ‘MyreCaptcha’ button from the top right corner

2. Login with your Google Account.
After successful login, you will find below box to setup your website.

3. Enter label to give an identity for eg MyWebsite or MyBlog
Select Checkbox.
4. Enter domains. You may enter multiple domains (one domain per line).
You may enter localhost URL as well for testing/development mode.
5. Accept the Terms of Service.
Click on Register.

That’s all you have to do in Google reCAPTCHA Dashboard.

Once setup is done, you may find Keys, Client Side integration and Server side integration details.

Now it’s time for coding.

Create ASP.Net MVC application to integrate Google reCaptcha

In your view or HTML or ASPX page add this line in the head section.

<script src=''></script>

Add below line in View, wherever you want to display the reCAPTCHA to appear.

<div class="g-recaptcha" data-sitekey="6LclPHMUAAAAADmoO58kBwR2f64d7AJ_e-ZYHY5i"></div>

Now create a post method in MVC controller.
In my case, I have created a Login form to implement Google reCAPTCHA.

In below code, once captcha status is true then you may proceed to hit the database or any service based on your requirement.

        public ActionResult Login(UsersModel userModel, string returnURL = “”)
            var response = Request[“g-recaptcha-response”];
            string secretKey = “<your secret key>”;
            var client = new WebClient();
            var captchaResult = client.DownloadString(string.Format(“{0}&response={1}”, secretKey, response));
            var obj = JObject.Parse(captchaResult);
            var captchStatus = (bool)obj.SelectToken(“success”);
            ViewBag.CaptchaStat = captchStatus ? string.Empty : “reCaptcha Validation Failed”;
            if (captchStatus)
              //Write your next logic here

Above code executes at server side, if you want to execute at client side or without a page postback.
You have 2 ways to do it.

1. Either call Google reCAPTCHA API from Jquery. Validate and then execute your logic
2. You may use above server-side code using AJAX to avoid page post back.

Now if some enters username and password and click on submit button without checking ‘I’m not robot’ then a validation error will be shown to user.

recaptcha with mvc

Try this implementation and let me know your feedback via comment.

Please follow and like us:

Leave a Comment