Simple ASP.NET MVC reCAPTCHA Implementation

Grab your reCaptcha keys from google

Add HTML into page.

<div class="g-recaptcha" data-sitekey="{YOUR_CLIENT_SIDE_KEY}"></div>

Create helper class. Please note I'm interested only in success and ignore everything else.

public class CaptchaResponse
{
    [JsonProperty("success")]
    public bool Success { get; set; }
}

public class Captcha
{
    public static bool IsValid()
    {
        bool success = false;            
            
        using (WebClient wc = new WebClient())
        {
            try
            {
                string secret = "{YOUR_SECRET_SERVER_KEY}";
                string request = HttpContext.Current.Request["g-recaptcha-response"];
                string reply = wc.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, request));

                CaptchaResponse captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);

                success = captchaResponse.Success;
            }
            catch
            {
            }
        }

        return success;
    }
}

Modify action in controller.

public ActionResult Index(ContactView contactView)
{
	if (Captcha.IsValid() == false)
	{
		ViewBag.CaptchaMessage = "Please confirm you are not a robot";

		return View(contactView);
	}
}

That's it, no more hard to read nonsenses from images.


Back