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

The ASP.NET SimpleCaptcha 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 SimpleCaptcha 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, 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 reuslt 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 perform client-side captcha validation using JQuery Ajax.

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 4 CAPTCHA Component\Asp.Net\.NET\WebApp\SimpleAPI\CaptchaClientSideWorkflowSettingsExample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 CAPTCHA Component > ASP.NET > ASP.NET Examples > Run .NET Examples

Default.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>BotDetect ASP.NET CAPTCHA Options: Client-Side Workflow Settings Code Example</title>
    <link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
</head>
<body>
    <form runat="server" class="column" id="form1">
        <h1>BotDetect ASP.NET CAPTCHA Options: <br /> Client-Side Workflow Settings Code Example</h1>
        <fieldset>
            <legend>ASP.NET WebForm CAPTCHA Validation</legend>
            <p class="prompt"><label for="CaptchaCodeTextBox">Retype the characters from the picture:</label></p>
            <BotDetect:WebFormsSimpleCaptcha runat="server" ID="ExampleCaptcha"/>
            <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" CssClass="incorrect"></asp:Label>
            </div>
        </fieldset>
        <h4>Custom BotDetect Client-Side Events Debug Log</h4>
        <div id="output"></div>
    </form>

    <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  captchaStyleName ' + this.captchaStyleName + '\n  captchaId ' + this.captchaId); 
        });

        // custom javascript handler executed before Captcha sounds are played
        BotDetect.registerCustomHandler('prePlaySound', function() { 
            log('prePlaySound'); 
        });

        // custom javascript handler executed before Captcha images are reloaded
        BotDetect.registerCustomHandler('preReloadImage', function() { 
            log('preReloadImage\n  ' + format(this.image.src) + '\n  autoReload: ' + this.autoReloading); 
        });

        // custom javascript handler executed after Captcha images are reloaded
        BotDetect.registerCustomHandler('postReloadImage', function() { 
            log('postReloadImage\n  ' + format(this.image.src)); 
        });

        BotDetect.registerCustomHandler('onHelpLinkClick', function() { 
            log('onHelpLinkClick');
            this.followHelpLink = false; // abort help page opening
        });


        function startAsyncCaptchaValidation() {
            // BotDetect CAPTCHA object
            // this function must be called after the Captcha is displayed on the page, otherwise the
            // client-side object won't be initialized
            var captcha = BotDetect.getInstanceByStyleName('ExampleCaptcha');
		
            if (captcha === null) {
                return;
            }
		
            // BotDetect client-side validation url
            var validationUrl = captcha.validationUrl;
		
            // captcha code
            var captchaCode = $('#CaptchaCodeTextBox').val();
		
            $.ajax({
                method: "GET",
                url: validationUrl,
                data: {
                    i: captchaCode
                },
                beforeSend: function() {
                    log('pre ajax validate\n  ' + format(validationUrl + '&i=' + captchaCode));
                },
                success: function(response) {
                    if (response) {
                        log('ajax validation passed');
                    } else {
                        log('ajax validation failed');
                        captcha.reloadImage();
                    }
                }
            });
        }
  </script>
</body>
</html>

Default.aspx.cs

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;
      }
      else
      {
        CaptchaCorrectLabel.Visible = false;
        CaptchaIncorrectLabel.Visible = true;
      }
    }
  }
}

Web.config

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please 
  visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
  </appSettings>
  <system.web>
  <httpHandlers>
    <!-- Register the HttpHandler used for BotDetect Simple API requests -->
    <add verb="GET" path="BotDetectCaptcha.ashx" 
    type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
  </httpHandlers>
  <pages controlRenderingCompatibilityVersion="4.5">
    <controls>
    <!-- Register the BotDetect tag prefix for easier use in all pages -->
    <add assembly="BotDetect" namespace="BotDetect.Web.UI" 
    tagPrefix="BotDetect"/>
    </controls>
  </pages>
  <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"/>
  </system.web>
  <system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <handlers>
    <!-- Register the HttpHandler used for BotDetect Simple API requests (IIS 7.0+) -->
    <remove name="BotDetectCaptchaHandler"/>
    <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" 
    path="BotDetectCaptcha.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
  </handlers>
  </system.webServer>
 </configuration>

botdetect.xml

<?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>ExampleCaptcha</name>
      <userInputID>CaptchaCodeTextBox</userInputID>
      <codeLength>3-5</codeLength>
    </captchaStyle>
  </captchaStyles>

</botdetect>

In botdetect.xml, we configure captcha options for the ExampleCaptcha captcha style name. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page .


Current BotDetect Versions