UncleCoder.com

UncleCoder.com

Free programming examples and instructions

ReCaptcha Asp.net

Demo and code for validating recaptcha 2 in Asp.net

by Athil


Posted on 31 Jan 2017 Category: Asp.net Views: 1267

Edited on 07 Aug 2017



Hi, Here I am going to show how to add Google ReCaptcha 2.0 in asp.net application.

 

DEMO

 For that, first I am going to design a contact form in asp.net, in that form contains a text for name, email, and message. 

After that go to the link https://www.google.com/recaptcha/admin#list and register your website on the red marked place in the image


 you will get a site key, secret key and script tag and a div tag

 

On Client Side

<div class="g-recaptcha" data-sitekey ......../div> 

 

is to paste on the place where you need a captcha each one will get different data site key so the captcha ill work only when the site is hosted in registered domain space.

<script src='https://www.google.com/recaptcha/api.js'></script>

Copy the script tag in your head section  

 

On the server side, you need to write the code for an HTTP post request.

public string recaptchaPost(string EncodedResponse)
        {

            using (WebClient client = new WebClient())
            {

                byte[] response =
                client.UploadValues("https://www.google.com/recaptcha/api/siteverify", new NameValueCollection()
                   {
                       { "secret", "6Lf**** ....................." },  /// Your Secret key copy from the site
                       { "response", EncodedResponse }

                   });

                string result = System.Text.Encoding.UTF8.GetString(response);

                return result;

            }
        }

Call the function from the page

string EncodedResponse = Request.Form["g-Recaptcha-Response"];

           string recaptchRespone =  recaptchaPost(EncodedResponse);
           dynamic json = JObject.Parse(recaptchRespone);

           if (json.success == true)
          {
                  // Recaptcha validating success
                  // Contact code here
           }
           else
          { 

                      // Recaptcha validating fail
           }

g-Recaptcha-Response need to load the page, each time the value will be different.

This captcha will not work in localhost, you need to upload the website on the registered domain space, you can register subdomains also to check its working.

From Local host

From registered server

Related Post

Recaptcha in Update panel



Leave a Comment:

                 

shiva kumar Tuesday,27 Jun 2017

hai
                 

Athil Thursday,29 Jun 2017

Hai Shiva

Advertisement