-->

how to use google recaptcha in asp.net.




Introduction

In this post, I am explain how to use google recaptcha in asp.net.

Google reCAPTCHA  is a free service from Google that helps protect websites from spam and abuse that restricts the automated input sent by a system and allows only input from a real human.

We can create a CAPTCHA in many ways but Google provides a free reCAPTCHA with better security without any cost.

Let us learn about  how to use google recaptcha in asp.net

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Sign up & Generate Key for Google reCaptcha.

Go to http://www.google.com/recaptcha > Sign up for Google reCaptcha > Create Key(for Google reCaptcha).

Step-3: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-4: Create table for Save Data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below


Step-5: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-6: Add a Webpage and Design for use Google Captcha.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code
            <h3>Contact Us form in ASP.NET with Google Captcha</h3>
            <div>
                <table>
                    <tr>
                        <td>Full Name:</td>
                        <td>
                            <asp:TextBox ID="txtFullName" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td>Email:</td>
                        <td>
                            <asp:TextBox ID="txtEmail" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td>Contact No:</td>
                        <td>
                            <asp:TextBox ID="txtContactNo" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td>Query</td>
                        <td>
                            <asp:TextBox ID="txtQuery" runat="server" TextMode="MultiLine" Height="66px" Width="297px" />
                        </td>
                    </tr>
                    <tr>
                        <td>Security Code</td>
                        <td>
                            <%--  We Can get the code from : https://developers.google.com/recaptcha/docs/display  --%>                    <%-- Here Please place you public key(google captcha public key) your_public_key--%>
                            <%-- Here Please place you public key(google captcha public key) your_public_key--%>
                            <script type="text/javascript"
                                 src="http://www.google.com/recaptcha/api/challenge?k=your_public_key">
                              </script>
                              <noscript>
                                 <iframe src="http://www.google.com/recaptcha/api/noscript?k=your_public_key"
                                     height="300" width="500" frameborder="0"></iframe><br>
                                 <textarea name="recaptcha_challenge_field" rows="3" cols="40">
                                 </textarea>
                                 <input type="hidden" name="recaptcha_response_field"
                                     value="manual_challenge">
                              </noscript>
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
                        </td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>
                            <asp:Label ID="lblMsg" runat="server" ></asp:Label>
                        </td>
                    </tr>
                </table>
            </div>
        

Step-7: Write this into Button Click event for validate captcha & Save data to database.


            
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtFullName.Text.Trim() == "")
            {
                lblMsg.Text = "Please provide your full name";
                return;
            }

            // here we will check captcha code is valid or not

            var isValidDic = CaptchaValidate();
            string val = "";
            try
            {
                isValidDic.TryGetValue(true, out val);
                if (val == null)
                {
                    lblMsg.Text = "provided security code is not valid! please try again.";
                    return;
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = "provided security code is not valid! please try again.";
                return;
            }

            ContactQuery c = new ContactQuery
            {
                Fullname = txtFullName.Text.Trim(),
                 EmailID = txtEmail.Text.Trim(),
                  ContactNo = txtContactNo.Text.Trim(),
                   Query = txtQuery.Text.Trim()
            };
            // here MyDatabaseEntities is dbContext
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                dc.ContactQueries.Add(c);
                dc.SaveChanges();
                lblMsg.Text = "Successfully Done!";
                txtFullName.Text = "";
                txtEmail.Text = "";
                txtContactNo.Text = "";
                txtQuery.Text = "";
            }
        }
        

and here is the function...
            
            private Dictionary<bool,string> CaptchaValidate()
            {
                // Validate Captcha here
                var isValidDic = new Dictionary<bool, string>();
                string[] resultFromGoogle;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.google.com/recaptcha/api/verify");

                req.ProtocolVersion = HttpVersion.Version10;
                req.Timeout = 0x7530;
                req.Method = "POST";
                req.UserAgent = "reCAPTCHA/ASP.NET";
                req.ContentType = "application/x-www-form-urlencoded";
                string Fdata = string.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}",
                    new object[]{
                        HttpUtility.UrlEncode("your_private_key"),
                        HttpUtility.UrlEncode(Dns.GetHostEntry(Dns.GetHostName()).AddressList[1].ToString()), 
                        HttpUtility.UrlEncode(Request.Form["recaptcha_challenge_field"]), 
                        HttpUtility.UrlEncode(Request.Form["recaptcha_response_field"]) 
                    });

                byte[] resData = Encoding.ASCII.GetBytes(Fdata);
                using (Stream rStream = req.GetRequestStream())
                {
                    rStream.Write(resData, 0, resData.Length);
                }
                try
                {
                    using (WebResponse wResponse = req.GetResponse())
                    {
                        using (TextReader readStream = new StreamReader(wResponse.GetResponseStream(), Encoding.UTF8))
                        {
                            resultFromGoogle = readStream.ReadToEnd().Split(new string[] { "\n", @"\n" }, StringSplitOptions.RemoveEmptyEntries);
                        }
                    }
                }
                catch (WebException ex)
                {
                    isValidDic.Add(false, ex.InnerException.ToString());
                    return isValidDic;
                }

                isValidDic.Add(resultFromGoogle[0] == "true", resultFromGoogle[1]);
                return isValidDic;
            }
        

Step-8: Run Application.


Download     Live Demo

Related Post :

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.