How To Add BotDetect CAPTCHA Protection to ASP.NET MVC 3.0 Applications (BotDetect v3.0; deprecated)

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

First Time Here?

Check the BotDetect ASP.NET MVC Captcha 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 samples coming with the BotDetect installation.

You can reuse the sample 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 samples 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.UI.Mvc.dll assembly. If you didn't change the installation folder during BotDetect setup, they can both be found in C:\Program Files\Lanapsoft\BotDetect 3 CAPTCHA Component\Asp.Net\v4.0\.

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:

  <!-- configure Session State for BotDetect use -->
  <sessionState mode="InProc" cookieless="AutoDetect" timeout="20" 
    sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>

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

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

In essence:

  • ASP.NET Session state is required for BotDetect, and a custom sessionIDManagerType is recommended to ensure proper Captcha sound functionality in older browsers. Both are explained in detail in the BotDetect ASP.NET Persistence FAQ.
  • 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.

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.UI.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 *@
@{ MvcCaptcha registrationCaptcha = CaptchaHelper.GetRegistrationCaptcha(); }
@if (!registrationCaptcha.IsSolved) {
  <div class="editor-label">
    @Html.LabelFor(m => m.CaptchaCode)
    @Html.Captcha(registrationCaptcha)
  </div>
  <div class="editor-field">
    @Html.TextBoxFor(m => m.CaptchaCode)
    @Html.ValidationMessageFor(m => m.CaptchaCode)
  </div>
}

The @using statement includes the BotDetect namespace.

Since the BotDetect layout stylesheet should be included in the generated Html <head> element, we add the stylesheet link in the BotDetectStyles section, which should be declared in the application layout declaration, just before the closing </head> tag.

Views/Shared/_Layout.cshtml
@* allow BotDetect stylesheet includes in selected Views *@
  @RenderSection("BotDetectStyles", required: false)
</head>

The Captcha markup is generated by the HtmlHelpers referencing the declared Model field and a MvcCaptcha instance. To keep the View code simple and make Captcha property setting code easier to write, it's best to move the MvcCaptcha object creation to a helper class included in the application.

CaptchaHelper.cs
using BotDetect;
using BotDetect.Web;
using BotDetect.Web.UI;
using BotDetect.Web.UI.Mvc;

public class CaptchaHelper
{
    public static MvcCaptcha GetRegistrationCaptcha()
    {
        // create the control instance
        MvcCaptcha registrationCaptcha = new MvcCaptcha("RegistrationCaptcha");
        registrationCaptcha.UserInputClientID = "CaptchaCode";

        // all Captcha settings have to be saved before rendering
        registrationCaptcha.SaveSettings();

        return registrationCaptcha;
    }
}
Please note how the MvcCaptcha control was given a unique name, and the UserInputClientID 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 CaptchaValidation attribute:

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

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

The CaptchaValidation attribute takes three parameters:

  • name of the Model field containing the Captcha code
  • MvcCaptcha 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 allows detailed customization of many Captcha properties, and you can read more about them in the BotDetect Captcha configuration How To.


Please Note

The information on this page is out of date and applies to a deprecated version of BotDetect™ CAPTCHA (v3.0).

An up-to-date equivalent page for the latest BotDetect Captcha release (v4) is BotDetect v4 Captcha documentation index.

General information about the major improvements in the current BotDetect release can be found at the What's New in BotDetect v4.0 page.