ASP.NET CAPTCHA Validator C# Code Example

First Time Here?

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

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

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 SimpleCaptcha Validator example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET\WebApp\SimpleAPI\WebFormsValidatorCaptchaExample\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 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>BotDetect CAPTCHA ASP.NET Validator Example</title>

</head>
<body>
  <form id="form1" runat="server">
    <h1>BotDetect CAPTCHA ASP.NET Validator Example</h1>
    <fieldset>
      <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
       </asp:RequiredFieldValidator>

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

      <div class="validationDiv">
        <asp:TextBox ID="CaptchaCodeTextBox" runat="server"></asp:TextBox>
        <BotDetect:SimpleCaptchaValidator 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
        </BotDetect:SimpleCaptchaValidator>

        <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" />
      </div>
    </fieldset>
  </form>
</body>
</html>

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

Default.aspx.cs

using System;
public partial class _Default : System.Web.UI.Page
{
  protected void Page_PreRender(object sender, EventArgs e)
  {



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

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

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

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>

There are several BotDetect-related changes in the web.config file, including SimpleCaptcha HttpHandler registration, BotDetect tag prefix registration.

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>CaptchaCode</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 .