Google reCAPTCHA using HttpClient in ASP.NET


reCAPTCHA is a free service that protects your site from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart. With the new API, a significant number of your valid human users will pass the reCAPTCHA challenge without having to solve a CAPTCHA.

Building The Code

Before you start, visit this link and click on the Get reCAPTCHA button and follow the steps.

Let's Get started 

Step 1: Create a class or a method in your controller and add the code below.

        public async Task<string> GetRecaptcha()
            var response = HttpContext.Current.Request["g-recaptcha-response"];
            const string secretKey = "your secret key";
            var apiConsumer = new ApiConsumer();
            const string url = "";
            apiConsumer.BaseUri = new Uri(url);
            apiConsumer.ContentType = ApiConsumer.ApplicationJson;
            apiConsumer.ResourcePath = string.Format("api/siteverify?secret={0}&response={1}", secretKey, response);
            var resp = await apiConsumer.GetAsync();
            if (resp.IsSuccessStatusCode)
                var result = await resp.Content.ReadAsStringAsync();
                return result;
            return null;

Step 2: You can now call this in your MVC controller method:

  var recaptcha = await _utils.GetGoogleRecaptcha();
                    var obj = JObject.Parse(recaptcha);
                    var status = (bool)obj.SelectToken("success");
                    if (status)
                          //goto dashboard
                         //recaptcha failed
Note: I used the Netonsoft JObject to parse the server response.

Refer to this url for the Apiconsumer class implementation

Step 3: Adding the View
<script src='' type="text/javascript"></script>
   <div class="g-recaptcha" data-sitekey="sike key"> 
The Result:


Popular posts from this blog

Paystack In Asp.Net MVC

Solved: Jwt Authentication in Asp.Net Web Api And Mvc

Coingate in .Net