Rolling your own ASP.Net MVC reCAPTCHA Helper

Pieter van der Westhuizen, a professional freelance web & mobile developer and founder of Coalition Software.
Search for a command to run...

Pieter van der Westhuizen, a professional freelance web & mobile developer and founder of Coalition Software.
A recent requirement came up for configurable dynamic forms in a mobile application. There are a few dynamic form packages for Flutter, but I wanted a bit more control over the schema and behavior of the form. Here follows my attempt at creating dyna...

If you've ever written a mobile app with Flutter that integrates with an API, then you'll know that there are a lot of model objects that get passed between the app and the API. JSON Serialization in Flutter can also take a fair amount of boilerplate...

Back in May 2020, Microsoft announced a new feature for Azure Blob Storage called Blob Index. Essentially, this enables you to add key/value tags to your Blob objects and be able to query said Blob objects without having to use a separate service lik...

In my last post, "Using AWS Cognito with Xamarin Forms", I showed how to authenticate with Amazon Cognito using Xamarin Forms and the Xamarin.Essentials Web Authenticator. In this post, we'll go through the process of using the AWS Cognito Hosted UI ...

In this post, I'll show you how to quickly and easily set up user authentication for your Xamarin Forms app using Amazon Cognito. AWS Cognito is a user identity management solution by Amazon. It is a really easy way to add authentication to your appl...

I needed to add a CAPTCHA to a ASP.Net MVC web form recently. Since the ASP.Net Web Helpers Library is not compatible with ASP.NET MVC, I searched the web for another solution. I did find MvcReCaptcha, but unfortunately the projects were a little out of date.

Rolling my own
I found a great solution from Chase Florell on StackOverflow. However it was in VB, so I’ve decided to share the C# version with you.
First, download the reCAPTCHA .NET Library and add the Recaptcha.dll file to your project references.

Next, in your ASP.Net MVC project, create a new folder called Helpers. In this folder create a class and call it ReCaptchaHelper.cs

Create a static method in the class called ReCAPTCHA, the code listing for the class looks as follows:
public class ReCaptchaHelper
{
public static MvcHtmlString ReCAPTCHA()
{
MvcHtmlString captchaHtml;
using (Recaptcha.RecaptchaControl captchaControl =
new Recaptcha.RecaptchaControl {
ID = "ReCaptcha",
Theme = "Clean",
PublicKey = "--YourPublicKey--",
PrivateKey = "--YourPrivateKey--" })
{
using (HtmlTextWriter htmlWriter =
new HtmlTextWriter(new StringWriter()))
{
captchaControl.RenderControl(htmlWriter);
captchaHtml =
MvcHtmlString.Create(htmlWriter.InnerWriter.ToString());
}
}
return captchaHtml;
}
}
You need to add a Validation folder next and create a ValidateCaptchaAttribute.cs class in the folder.

The code listing for the class is:
public class ValidateCaptchaAttribute : ActionFilterAttribute
{
string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
string RESPONSE_FIELD_KEY = "recaptcha_response_field";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY] == null)
{
filterContext.ActionParameters["CaptchaIsValid"] = true;
return;
}
var captchaChallengeValue =
filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY];
var captchaResponseValue =
filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY];
var captchaValidator = new Recaptcha.RecaptchaValidator
{
PrivateKey = "--YourPrivateKey--",
RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
Challenge = captchaChallengeValue,
Response = captchaResponseValue
};
var recaptchaResponse = captchaValidator.Validate();
filterContext.ActionParameters["CaptchaIsValid"] =
recaptchaResponse.IsValid;
base.OnActionExecuting(filterContext);
}
}
To add a ReCAPTCHA to your view you simply need to use the ReCaptchaHelper:
@using (Html.BeginForm())
{
@ReCaptchaHelper.ReCAPTCHA()
<input type="submit" value="Go" />
}
You would need to add a @using to the top of your view in order for the helper to work e.g.:
@using YourWebsiteNameSpace.Helpers
Finally, in the Controller action for the view, you need to add the validation attribute:
[HttpPost]
[Validation.ValidateCaptcha()]
public ActionResult Index(bool captchaIsValid)
{
if (!captchaIsValid)
{
ModelState.AddModelError("recaptcha", "*");
}
return View();
}
When you run your project, you should now see a reCaptcha in your view, and when you post the form, if the captcha is valid, the captchaIsValid parameter should return true.

As easy as that and very handy!