ASP.NET CAPTCHA Validator C# Code Example

First Time Here?

Check the BotDetect ASP.NET WebForms Captcha Quickstart for key integration steps.

The ASP.NET Captcha Validator example project shows how to use the CaptchaValidator control to integrate BotDetect CAPTCHA validation with standard ASP.NET page validation functionality and other validator controls.

Download the BotDetect ASP.NET CAPTCHA Generator archive to run this example

Within this page, the root folder of the extracted archive is referred as the <BDC-DIR>.

This example is in the <BDC-DIR>/lgcy-on-lgcy/examples/t_api-captcha-webforms-api_basics-customvalidator/csharp/ folder; and contains the following files:


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">

<html xmlns="">
<head id="Head1" runat="server">
  <title>BotDetect CAPTCHA ASP.NET Validator Example</title>
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
  <form id="form1" runat="server">
    <h1>BotDetect CAPTCHA ASP.NET Validator Example</h1>
      <legend>CAPTCHA Validator</legend>
      <p class="prompt">Name:</p>
      <asp:TextBox ID="NameTextBox" runat="server"></asp:TextBox>
      <asp:RequiredFieldValidator ID="NameValidator" runat="server"
        ControlToValidate="NameTextBox" ErrorMessage="Your name is required"
        EnableClientScript="true" SetFocusOnError="true">
          Missing name

      <p class="prompt">
        <label for="CaptchaCodeTextBox">Retype the characters from the picture:</label>
      <BotDetect:WebFormsCaptcha ID="ExampleCaptcha" runat="server" />

      <div class="validationDiv">
        <asp:TextBox ID="CaptchaCodeTextBox" runat="server"></asp:TextBox>
        <BotDetect:CaptchaValidator ID="ExampleCaptchaValidator" runat="server"
          ControlToValidate="CaptchaCodeTextBox" CaptchaControl="ExampleCaptcha"
          ErrorMessage="Retype the characters exactly as they appear in the picture"
          EnableClientScript="true" SetFocusOnError="true">
            Incorrect CAPTCHA code

        <br />
        <asp:Label ID="ValidationPassedLabel" runat="server" CssClass="correct" 
        Visible="False" Text="Validation passed!" />

        <br />
        <asp:Button ID="SumbitButton" runat="server"
          Text="Submit" CausesValidation="true" />

Instead of validating the user's Captcha code input in page code-behind, we add a <BotDetect:CaptchaValidator> control to the page, and wire it up to process Captcha validation attempts by specifying the ControlToValidate (user input textbox) and CaptchaControl (Captcha instance) attributes.


using System;
public partial class _Default : System.Web.UI.Page
  protected void Page_PreRender(object sender, EventArgs e)
    // setup client-side input processing
    ExampleCaptcha.UserInputID = CaptchaCodeTextBox.ClientID;

    if (IsPostBack)
      // clear previous user input
      CaptchaCodeTextBox.Text = null;

      if (Page.IsValid)
        ValidationPassedLabel.Visible = true;
        ValidationPassedLabel.Visible = false;

Since the CaptchaValidator is active on the page, we can simply use Page.IsValid checks around protected code, and Captcha validation will be performed automatically during Page validation. This option can be useful when combining BotDetect Captcha validation with integrated validation of other form fields.


<?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" tagPrefix="BotDetect" />
    <compilation debug="false" targetFramework="4.5" />
    <httpRuntime requestValidationMode="4.5" targetFramework="4.5" 
    encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=, 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" />

There are several BotDetect-related changes in the web.config file, including Captcha HttpHandler registration, ASP.NET Session state configuration, and BotDetect tag prefix registration.