How to implement Google reCaptcha in asp.net MVC application without API

Introduction

In this post, I am explain how to implement Google reCaptcha in asp.net MVC application without API.

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 implement Google reCaptcha in asp.net MVC application without API.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > 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: Create a Controller .

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller "ContactController"

Step-7: Add new action into your controller for Get Method

Here I have added "Query" Action into "Contact" Controller. Please write this following code

            namespace MVCGoogleReCaptcha.Controllers
            {
                public class ContactController : Controller
                {
                    public ActionResult Query()
                    {
                        return View();
                    }
               }
          }
        

[N:B: Rebuild your application here before Add View]

Step-8: Add view for your Action & design for create form.

Right Click on Action Method (here right click on Query action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Select Scaffold templete "Create" > Add.
HTML Code (View)
            @model MVCGoogleReCaptcha.QueryData

            @{
                ViewBag.Title = "Query";
            }

            <h2>Query</h2>

            @using (Html.BeginForm()) {
                @Html.ValidationSummary(true)
                if (ViewBag.Message != null)
                {
                    <div style="font-weight:bold; color:red; border:1px solid black">
                        @ViewBag.Message
                    </div>
                }
                <fieldset>
                    <legend>Query Data</legend>
        

                    <div class="editor-label">
                        @Html.LabelFor(model => model.FullName)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.FullName)
                        @Html.ValidationMessageFor(model => model.FullName)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.EmailID)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.EmailID)
                        @Html.ValidationMessageFor(model => model.EmailID)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.ContactNo)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.ContactNo)
                        @Html.ValidationMessageFor(model => model.ContactNo)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Query)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Query)
                        @Html.ValidationMessageFor(model => model.Query)
                    </div>
                    @* I Will Place Google Re-Captcha Here *@
                    <div class="editor-label">
                        Security Code
                    </div>
                    <div class="editor-label">
                        @* You Can get the Script code from https://developers.google.com/recaptcha/docs/display *@
                        <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>
                    </div>
                    <p>
                        <input type="submit" value="Create" />
                    </p>
                </fieldset>
            }

            <div>
                @Html.ActionLink("Back to List", "Index")
            </div>

            @section Scripts {
                @Scripts.Render("~/bundles/jqueryval")
            }
        

Step-9: Add new action into your controller for POST Method

Here I have added "Query" Action with Model Parameter (here "Contact") into "Contact" Controller. Please write this following code

            [HttpPost]
            public ActionResult Query(QueryData qd)
            {
                if (ModelState.IsValid)
                {
                    // Here I will check is captcha code is valid or not
                    bool isCaptchaCodeValid = false;
                    string CaptchaMessage = "";
                    isCaptchaCodeValid = GetCaptchaResponse(out CaptchaMessage);

                    if (isCaptchaCodeValid)
                    {
                        // Save Data Here
                        using (MyDatabaseEntities dc = new MyDatabaseEntities())
                        {
                            dc.QueryDatas.Add(qd);
                            dc.SaveChanges();
                            ModelState.Clear();
                            qd = null;
                            ViewBag.Message = "Query Saved Successfully";
                        }
                    }
                    else
                    {
                        ViewBag.Message = CaptchaMessage;
                    }
                }
                return View(qd);
            }
        

Here is the function for get response from google api about validation of captcha code.

            private bool GetCaptchaResponse(out string message)
            {
                bool flag = false;
                message = "";

                string[] result;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/recaptcha/api/verify");
                request.ProtocolVersion = HttpVersion.Version10;
                request.Timeout = 0x7530;
                request.Method = "POST";
                request.UserAgent = "reCAPTCHA/ASP.NET";
                request.ContentType = "application/x-www-form-urlencoded";
                string formData = 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[] formbytes= Encoding.ASCII.GetBytes(formData);

                using (System.IO.Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(formbytes, 0, formbytes.Length);

                }

                try
                {
                    using (WebResponse httpResponse = request.GetResponse())
                    {
                        using (System.IO.TextReader readStream = new System.IO.StreamReader(httpResponse.GetResponseStream(),Encoding.UTF8))
                        {
                            result = readStream.ReadToEnd().Split(new string[] { "\n", @"\n" }, StringSplitOptions.RemoveEmptyEntries);
                            message = result[1];
                            flag = Convert.ToBoolean(result[0]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    return false;
                }
                return flag;
            }
        

Step-10: Run Application.


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.