How To Add BotDetect CAPTCHA Protection to ASP.NET MVC 3.0 Applications

BotDetect ASP.NET Captcha Simple API protection can be added to your ASP.NET MVC 3.0 and older applications using the MvcSimpleCaptcha class, a BotDetect HtmlHelper and a custom ActionFilterAttribute implemented in the BotDetect.Web.Mvc.dll assembly.

First Time Here?

Check the BotDetect ASP.NET MVC Captcha Simple API Quickstart for key integration steps.

You can also see how BotDetect Captcha protection has been added to the starting ASP.NET MVC application by running the BotDetect Captcha ASP.NET MVC integration code examples coming with the BotDetect installation.

You can reuse the example projects source code (both C# and VB.NET are available) that fits your application requirements.

CAPTCHA Integration Steps

To keep the demonstration code simple, we will show the steps required to add BotDetect to an ASP.NET MVC 3.0 application using C# and the Razor view engine. Integration steps are similar for VB.NET, ASP.NET MVC 2.0 or 1.0 applications, and ASPX views – the results and differences can be seen in the code examples mentioned above.

Configure Your ASP.NET MVC Application to Use BotDetect

Before Captcha validation can be included in any particular action, BotDetect must first be added to the application.

Add BotDetect ASP.NET MVC CAPTCHA References

ASP.NET MVC applications should reference the base BotDetect.dll assembly, as well as the MVC-specific BotDetect.Web.Mvc.dll assembly. If you didn't change the installation folder during BotDetect setup, they can both be found in C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET\.

Add SQLite Reference

By default, BotDetect ASP.NET CAPTCHA Simple API uses SQLite as the default persistence provider for storing captcha data, so you need to ensure SQLite assembly is referenced in your project. Here is where you can find the SQLite installation guide. Or check any Simple API examples that are installed with BotDetect.

Register BotDetect in Web.config

There are several changes that need to be made to your application configuration to allow it to use BotDetect Captcha protection. Here is how a properly configured web.config segment looks like:

<system.web>
  <httpHandlers>
    <!-- register HttpHandler used for BotDetect Simple API requests -->
    <add verb="GET" path="BotDetectCaptcha.ashx" 
      type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
  </httpHandlers>
</system.web>

<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  <handlers>
    <!-- register HttpHandler used for BotDetect Simple API requests -->
    <remove name="BotDetectCaptchaHandler"/>
    <add name="BotDetectCaptchaHandler" preCondition="integratedMode" 
      verb="GET" path="BotDetectCaptcha.ashx" 
      type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
  </handlers>
</system.webServer>

In essence:

  • BotDetect uses a special HttpHandler for Captcha requests (Captcha images, sounds, resources...), which needs to be registered in your application. For IIS 7 compatibility, the handler has to be registered in both the <system.web> and <system.webServer> configuration sections.

Configure Captcha options

Configure captcha options in botdetect.xml configuration file. By default, this file is located at the root of your project.

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/net"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://captcha.com/schema/net 
     https://captcha.com/schema/net/botdetect-4.4.0.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>RegistrationCaptcha</name>
      <userInputID>CaptchaCode</userInputID>
      <codeLength>3-5</codeLength>
    </captchaStyle>
  </captchaStyles>

</botdetect>

Add CAPTCHA Validation to a MVC Controller action

Adding Captcha validation to the selected Controller action requires minor changes in the relevant Model, View and Controller source code.

CAPTCHA Validation Model

First, Captcha code should be added as a string field to the related Model declaration.

Models/AccountModels.cs
public class RegisterModel
{
  ...

  // add Captcha code as a field in the protected action Model
  [Required(ErrorMessage = "Retyping the characters from the picture 
    is required.")]
  [Display(Name = "Please retype the characters from the picture")]
  public string CaptchaCode { get; set; }
}

CAPTCHA Validation View

Captcha validation elements can then be added to the relevant View declaration.

Views/Account/Register.cshtml
@using BotDetect.Web.Mvc;

@* add BotDetect header includes *@
@section BotDetectStyles {
  <link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl" 
    rel="stylesheet" type="text/css" />
}

  ...

@* add Captcha validation controls to the protected action View *@
@{ MvcSimpleCaptcha registrationCaptcha = MvcSimpleCaptcha("RegistrationCaptcha"); }

  <div class="editor-label">
    @Html.LabelFor(m => m.CaptchaCode)
    @Html.SimpleCaptcha(registrationCaptcha)
  </div>
  <div class="editor-field">
    @Html.TextBoxFor(m => m.CaptchaCode)
    @Html.ValidationMessageFor(m => m.CaptchaCode)
  </div>

The @using statement includes the BotDetect namespace.

Please note how the MvcSimpleCaptcha control was given a unique name, and the UserInputID property was set to the same name we gave to the Model property keeping the Captcha code.

CAPTCHA Validation Controller

Adding Captcha validation to the selected Controller action is then as simple as adding the SimpleCaptchaValidation attribute:

Controllers/AccountController.cs
using BotDetect.Web.UI.Mvc;

public class AccountController : Controller
{
  ...  
    
  [HttpPost]
  [SimpleCaptchaValidation("CaptchaCode", "RegistrationCaptcha", "Your input 
    doesn't match displayed characters.")]
  public ActionResult Register(RegisterModel model)
  {
    if (ModelState.IsValid)
    {
      ...
    

The SimpleCaptchaValidation attribute takes three parameters:

  • name of the Model field containing the Captcha code
  • MvcSimpleCaptcha instance name
  • error message that will be displayed when Captcha validation fails

If everything has been configured correctly, the above ActionFilterAttribute will automatically add the appropriate ModelState error when Captcha validation fails.

Further CAPTCHA Customization

BotDetect ASP.NET Captcha Simple API allows detailed customization of many Captcha properties, and you can read more about them in the BotDetect SimpleCaptcha Options configuration How To.