Google's New reCAPTCHA Api in Asp.Net using C# with Example

In thistutorial i will explain how to use Googles new reCAPTCHA api in Asp.net website using C# with example. or How to implement Google New reCaptcha I am not a robot in Asp.Net using C#. reCaptcha is a free service provided by google which helps to fight against spams and bots. Google has launched a new version of reCaptcha which is very much secure compare to older version of Captcha and it is good user friendly from previous versions of Captcha. 

Google's New reCAPTCHA

So, let's Create one example to implement Google's new reCAPTCHA api in Asp.net.

Before you start implement reCAPTCHA in your website you need to register your web application at google's reCaptcha website. For Register your website at google's reCaptcha you need to visit google's reCaptcha website and you have to login with your existing google account or register google account and then click on "Get reCaptcha" button.

When you will click on "Get reCaptcha" button you can see following screen where you need to add your Domain Name in domains section. After successfully add your domain name you need to click on register button for generate Secret Key and Sitekey.


Now you have to add following script/code into head section.
<script src='https://www.google.com/recaptcha/api.js'></script>
After link Script with your website you need to write aspx code.
aspx code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        body
        {
            font11px verdana;
        }
        .auto-style1 {
            text-aligncenter;
            font-sizex-large;
            color#FF9900;
        }
        .auto-style2 {
            text-aligncenter;
            color#FF9900;
        }
    </style>
 
    <script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
    <form id="form1" runat="server">
        <table align="center">
            <tr>
                <td class="auto-style1">
                    <strong>www.asppoint.com</strong></td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    <center>
                    <div class="g-recaptcha" 
                         data-sitekey="Your-Site-Key">
                       <%-- replace data-sitekey = "Your-Site-Key" with
                        your new generated sitekey--%>
                    </div>
                    <center>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    <center>
                    <asp:Label ID="lbl_Msg" runat="server"
                         Font-Bold="true" 
                         Font-Size="Medium" />
                    </center>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    <center>
                    <asp:Button ID="btn_ReCaptcha" runat="server" 
                         Text="Validate" 
                         BackColor="#3366FF"
                         BorderStyle="None" 
                         ForeColor="White" 
                         Height="37px" 
                         Width="82px"
                         OnClick="btn_ReCaptcha_Click" />
                     </center>
                </td>
            </tr>
            <tr>
                <td class="auto-style2">
                    <strong>Developed by: Nikunj Satasiya</strong></td>
            </tr>
        </table>
    </form>
</body>
</html>
Note: Replace data-sitekey="Your-Site-Key" with your new generated sitekey.
Now before write c# code you have to add following namespace in code behind.
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.IO;

C# Code For Googles new reCAPTCHA api in Asp.Net

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void btn_ReCaptcha_Click(object sender, EventArgs e)
    {
        //start building recaptch api call
        var CaptchaApi = new StringBuilder();
        CaptchaApi.Append("https://www.google.com/recaptcha/api/siteverify?secret=");
 
        //secret key
        var Key = " YOUR-SECRET-KEY ";
        CaptchaApi.Append(Key);
 
        //This code for response from recaptch control
        CaptchaApi.Append("&");
        CaptchaApi.Append("response=");
        var reCaptchaResponse = Request["g-recaptcha-response"];
        CaptchaApi.Append(reCaptchaResponse);
 
        //////////////////////////////////// "Optional" ///////////////////////////////////
        //This code for client ip address
        //---- This Ip address part is optional. If you donot want to send IP address you can
        //---- Skip(Remove below 4 lines)
        CaptchaApi.Append("&");
        CaptchaApi.Append("remoteip=");
        var clientIpAddress = GetUserIp();
        CaptchaApi.Append(clientIpAddress);
        //////////////////////////////////// "Optional" ///////////////////////////////////
 
        //This code for make the api call and determine validity
        using (var client = new WebClient())
        {
            var Captcha = CaptchaApi.ToString();
            var json = client.DownloadString(Captcha);
            var serializer = new DataContractJsonSerializer(typeof(RecaptchaApiResponse));
            var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
            var result = serializer.ReadObject(ms) as RecaptchaApiResponse;
 
            //This code for Check if we are able to call api or not.
            if (result == null)
            {
                lbl_Msg.Text = "Captcha was unable to make the api call";
            }
            else // If Yes
            {
                //api call contains errors
                if (result.ErrorCodes != null)
                {
                    if (result.ErrorCodes.Count > 0)
                    {
                        foreach (var error in result.ErrorCodes)
                        {
                            lbl_Msg.Text = "reCAPTCHA Error: " + error;
                        }
                    }
                }
                else //api does not contain errors
                {
                    if (!result.Success) //captcha was unsuccessful for some reason
                    {
                        lbl_Msg.Text = "Captcha Did Not Verified, Please Try Again.";
                    }
                    else //---- If successfully verified. Do your rest of logic.
                    {
                        lbl_Msg.Text = "Captcha Successfully Verified..! ";
                    }
                }
 
            }
 
        }
    }
 
    [DataContract]
    public class RecaptchaApiResponse
    {
        [DataMember(Name = "success")]
        public bool Success;
 
        [DataMember(Name = "error-codes")]
        public List<string> ErrorCodes;
    }
 
    //////////////////////////////////// "Optional" ///////////////////////////////////
    //This code for get user IP
    private string GetUserIp()
    {
        var usersIpAdd = string.Empty;
 
        if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            usersIpAdd = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        }
        else if (!string.IsNullOrEmpty(Request.UserHostAddress))
        {
            usersIpAdd = Request.UserHostAddress;
        }
        return usersIpAdd;
    }
}
Note: Change var Key = " YOUR-SECRET-KEY " with your Secret Key.

Demo:
Google's new reCaptcha in Asp.Net

Previous
Next Post »

If you have any kind of question about any post, Feel free to ask.You can simply drop a comment below post. Your feedback and suggestions will be highly appreciated. ConversionConversion EmoticonEmoticon