ASP.NET MVC CAPTCHA implementation

Use NuGet and install Recaptcha for .NET (supports MVC as well)

http://nuget.org/packages/RecaptchaNet/

Documentation is on the site:

http://recaptchanet.codeplex.com/

There are other captchas:

http://captchamvc.codeplex.com/

EDIT:

This project has moved to GitHub https://github.com/tanveery/recaptcha-net


NuGet Google reCAPTCHA V2 for MVC 4 and 5

  • NuGet Package
  • Demo And Document

Web.config File in the appSettings section of your web.config file, add the keys as follows:

<appSettings>
   <add name="reCaptchaPublicKey" value="Your site key" />
   <add name="reCaptchaPrivateKey" value="Your secret key" />
</appSettings>

Add Recaptcha in your view.

@using reCAPTCHA.MVC
@using (Html.BeginForm())
{
    @Html.Recaptcha()
    @Html.ValidationMessage("ReCaptcha")
    <input type="submit" value="Register" />
}

Verifying the user's response.

[HttpPost]
[CaptchaValidator]
public ActionResult Index(RegisterModel registerModel, bool captchaValid)
{
    if (ModelState.IsValid)
    {
    }
    return View(registerModel);
}

EDIT:

You should also add this in your head tag or you might see improper captcha

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

First off, it looks like you are mixing standard ASP.NET and ASP.NET MVC. If you want to do MVC, the standard way to do it is the Html.TextBoxFor() type of stuff, and then you handle the value of that in a controller action method rather than write something inline in the page. So you have something like this:

Page.aspx
<rhcap:Captcha ID="Captcha1" runat="server"></rhcap:Captcha>
<%= Html.TextBoxFor(m => m.UserCaptcha) %>

and then in:

SomeController.cs

[HttpGet]
public ActionResult Page()
{
    // generate captcha code here
    ControllerContext.HttpContext.Session["Captcha"] = captchaValue;
    return View(new PageViewModel());
}

[HttpPost]
public ActionResult Page(PageViewModel model)
{
    if (model.UserCaptcha == ControllerContext.HttpContext.Session["Captcha"])
    {
        // do valid captcha stuff
    }
}

To take this to the next level would be to implement it in a FilterAttribute. But this should work for most uses.