ASP.NET CAPTCHA Client-Side Workflow Settings C# Code Example

The ASP.NET Captcha client-side workflow settings example project shows how to use custom BotDetect CAPTCHA client-side events to execute user-defined JavaScript code at various stages of the Captcha challenge workflow.

First Time Here?

Check the BotDetect Developer Crash Course for key integration steps.

Client-side Captcha object initialization, Captcha image reloading, Captcha sound playback, built-in Captcha Ajax validation, and Captcha help link clicks all have a number of related client-side "events" and hooks where user-defined client-side callbacks can be injected.

User code can be associated with Captcha workflow events using the BotDetect.RegisterCustomHandler() function, as shown in the example JavaScript code.

Loading the form will initialize the client-side Captcha object (created by the BotDetect.Init() JavaScript call included in Captcha markup), and result in the PostInit event.

Clicking the Captcha sound icon will result in the PrePlaySound event before the audio elements are added to the page DOM. There is no PostPlaySound event since not all browsers allow user callbacks when browser sound playing finishes.

Clicking the Captcha reload icon will result in PreReloadImage and PostReloadImage events, executed before and after the Http request loading the new Captcha image from the server.

Clicking the Captcha image (i.e. the included Captcha help link) will result in the OnHelpLinkClick event.

Typing in a Captcha code and clicking the Validate button will first result in the PreAjaxValidate event, and later in either AjaxValidationFailed or AjaxValidationPassed depending on whether the server responds that the typed-in Captcha code was correct or not. In case of Ajax asynchronous request errors, AjaxValidationError will be called.

Download the BotDetect ASP.NET CAPTCHA Component and run this example

Visual Studio 2005-2017 / .NET 2.0 and onwards

By default, the .NET C# version of the ASP.NET Captcha client-side workflow settings example project is installed at:
C:\Program Files\Captcha Inc\BotDetect CAPTCHA\aspnetlegacy+netlegacy\Examples\TraditionalAPI\CaptchaClientSideWorkflowSettingsExample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect CAPTCHA > ASPNETLEGACY + NETLEGACY Examples > Legacy ASP.NET + Legacy .NET Run code examples


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
Inherits="_Default" %> 

<!DOCTYPE html> 

<html xmlns=""> 
<head id="Head1" runat="server"> 
  <title>BotDetect ASP.NET CAPTCHA Options: Client-Side Workflow Settings Code 
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" /> 
  <form runat="server" class="column" id="form1"> 
    <h1>BotDetect ASP.NET CAPTCHA Options: 
      <br /> 
      Client-Side Workflow Settings Code Example</h1> 
      <legend>ASP.NET WebForm CAPTCHA Validation</legend> 
      <p class="prompt"> 
        <label for="CaptchaCodeTextBox">Retype the characters from the picture:</label></p> 
      <BotDetect:WebFormsCaptcha runat="server" ID="ExampleCaptcha" 
      UserInputControlID="CaptchaCodeTextBox" /> 
      <div class="validationDiv"> 
        <asp:TextBox ID="CaptchaCodeTextBox" runat="server"></asp:TextBox> 
        <asp:Button ID="ValidateCaptchaButton" runat="server" 
        OnClientClick="startAsyncCaptchaValidation(); return false;" /> 
        <asp:Label ID="CaptchaCorrectLabel" runat="server" CssClass="correct"></asp:Label> 
        <asp:Label ID="CaptchaIncorrectLabel" runat="server" 
    <h4>Custom BotDetect Client-Side Events Debug Log</h4> 
    <div id="output"></div> 

  <script type="text/javascript"> 
    function log(text) { 
      var output = document.getElementById('output'); 
      var line = document.createElement('pre'); 
      line.innerHTML = timestamp() + ' ' + text; 
      output.insertBefore(line, output.firstChild); 

    function timestamp() { 
      return new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1"); 

    function format(url) { 
      return url.replace(/^.*?\?/g, '').replace(/&/g, '\n  &'); 

    BotDetect.RegisterCustomHandler('PostInit', function () { 
      log('PostInit \n  CaptchaId ' + this.Id + '\n  InstanceId ' + this. 

    // custom javascript handler executed before Captcha sounds are played 
    BotDetect.RegisterCustomHandler('PrePlaySound', function () { 

    // custom javascript handler executed before Captcha images are reloaded 
    BotDetect.RegisterCustomHandler('PreReloadImage', function () { 
      log('PreReloadImage\n  ' + format(this.Image.src) + '\n  AutoReload: ' + 

    // custom javascript handler executed after Captcha images are reloaded 
    BotDetect.RegisterCustomHandler('PostReloadImage', function () { 
      log('PostReloadImage\n  ' + format(this.Image.src)); 

    // register handlers for the four steps of the BotDetect Ajax validation  
    // workflow 
    BotDetect.RegisterCustomHandler('PreAjaxValidate', function () { 
      log('PreAjaxValidate\n  ' + format(this.ValidationUrl + '&i=' + this. 

    BotDetect.RegisterCustomHandler('AjaxValidationFailed', function () { 

    BotDetect.RegisterCustomHandler('AjaxValidationPassed', function () { 

    BotDetect.RegisterCustomHandler('AjaxValidationError', function () { 

    BotDetect.RegisterCustomHandler('OnHelpLinkClick', function () { 
      this.FollowHelpLink = false; // abort help page opening 

    function startAsyncCaptchaValidation() { 
      var input = document.getElementById('CaptchaCodeTextBox'); 
      if (input && 'text' == input.type) { 
        // call the BotDetect built-in client-side validation function 
        // this function must be called after the Captcha is displayed on the  
        // page, otherwise the 
        // client-side object won't be initialized 


using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

public partial class _Default : System.Web.UI.Page 
  protected void Page_PreRender(object sender, EventArgs e) 
    // initial page setup 
    if (!IsPostBack) 
      // set control text 
      ValidateCaptchaButton.Text = "Validate"; 
      CaptchaCorrectLabel.Text = "Correct!"; 
      CaptchaIncorrectLabel.Text = "Incorrect!"; 

      // these messages are shown only after validation 
      CaptchaCorrectLabel.Visible = false; 
      CaptchaIncorrectLabel.Visible = false; 

    if (IsPostBack) 
      // validate the Captcha to check we're not dealing with a bot 
      bool isHuman = ExampleCaptcha.Validate(); 
      if (isHuman) 
        CaptchaCorrectLabel.Visible = true; 
        CaptchaIncorrectLabel.Visible = false; 
        CaptchaCorrectLabel.Visible = false; 
        CaptchaIncorrectLabel.Visible = true; 


<?xml version="1.0"?> 
  For more information on how to configure your ASP.NET application, please  
    <section name="botDetect" requirePermission="false" 
    type="BotDetect.Configuration.BotDetectConfigurationSection, BotDetect"/> 
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/> 
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/> 
    <!-- Register the HttpHandler used for BotDetect Captcha requests --> 
    <add verb="GET" path="BotDetectCaptcha.ashx" 
    type="BotDetect.Web.CaptchaHandler, BotDetect"/> 
  <!-- Register a custom SessionIDManager for BotDetect Captcha requests --> 
  <sessionState mode="InProc" cookieless="AutoDetect" timeout="20" 
  sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/> 
  <!-- Session state is required for BotDetect storage; you can also turn if off  
  globally and only enable for BotDetect-protected pages if you prefer --> 
  <pages controlRenderingCompatibilityVersion="4.5" enableSessionState="true"> 
    <!-- Register the BotDetect tag prefix for easier use in all pages --> 
    <add assembly="BotDetect" namespace="BotDetect.Web.UI" 
  <compilation debug="false" targetFramework="4.5"/> 
  <httpRuntime requestValidationMode="4.5" targetFramework="4.5" 
  encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4. 
  0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> 
  <machineKey compatibilityMode="Framework45"/> 
  <validation validateIntegratedModeConfiguration="false"/> 
    <!-- Register the HttpHandler used for BotDetect Captcha requests (IIS 7.0+) --> 
    <remove name="BotDetectCaptchaHandler"/> 
    <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" 
    path="BotDetectCaptcha.ashx" type="BotDetect.Web.CaptchaHandler, BotDetect"/> 
  <botDetect helpLinkEnabled="true" helpLinkMode="image" />