ASP.NET Basic CAPTCHA C# Code Example

First Time Here?

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

The ASP.NET Basic Captcha Simple API example project shows the most basic source code required to protect an ASP.NET form with BotDetect CAPTCHA and validate the user input.

It can be used as a starting point when you are first learning how to use BotDetect.

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

Visual Studio 2005-2017 / .NET 2.0 and onwards

By default, the ASP.NET Basic Captcha Simple API example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET\WebApp\SimpleAPI\WebFormsBasicCaptchaExample\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


<%@ 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 Validation: Basic ASP.NET WebForms CAPTCHA 
  Code Example</title>

  <form runat="server" class="column" id="form1">
    <h1>BotDetect ASP.NET CAPTCHA Validation:
      <br />
      Basic ASP.NET WebForms CAPTCHA Code Example</h1>
      <legend>ASP.NET WebForm CAPTCHA Validation</legend>
      <p class="prompt">
        <label for="CaptchaCodeTextBox">Retype the characters from the picture:<
      <BotDetect:WebFormsSimpleCaptcha runat="server" ID="ExampleCaptcha"/>
      <div class="validationDiv">
        <asp:TextBox ID="CaptchaCodeTextBox" runat="server"></asp:TextBox>
        <asp:Button ID="ValidateCaptchaButton" runat="server" />
        <asp:Label ID="CaptchaCorrectLabel" runat="server" CssClass="correct"><
        <asp:Label ID="CaptchaIncorrectLabel" runat="server" 

As explained in the ASP.NET WebForms SimpleCaptcha howto guide, the <BotDetect:SimpleCaptcha> custom web control generates the Html markup required to show the Captcha image and the SimpleCaptcha sound / reload buttons. The form also contains an <asp:TextBox> for the user input, an <asp:Button> which submits the page, and a pair of <asp:Label> controls which are used to show the SimpleCaptcha validation result.


using System;
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;

Placing the Form Processing Code

As explained in the ASP.NET WebForms SimpleCaptcha howto guide, form submission processing is done in the Page_PreRender event handler, so all individual control events are executed before the SimpleCaptcha validation. If you want to validate the user's Captcha input before individual control events, you can also place the SimpleCaptcha validation code in the Page_Load event handler.

Note that the form processing is intentionally not done in the ValidateButton_Click handler, in case there are multiple controls which can submit the page. We want to validate the SimpleCaptcha regardless of what caused the page to be submitted.

This is important because most bots will not submit the form by actually clicking the button, but by simply constructing fake POST request data – which might or might not include the "control which caused postback" part responsible for triggering the individual button click event. Checking the SimpleCaptcha regardless of other form submission variables ensures proper SimpleCaptcha security in all cases.

Form Setup Code

On the first page load (if (!IsPostBack)), the button and label controls are initialized, and SimpleCaptcha validation is not performed (since the user didn't have a chance to solve it yet).

SimpleCaptcha Validation Code

When the page is submitted (if (IsPostBack)), we forward the user input to the SimpleCaptcha.Validate() method, which compares it to the correct code stored in Session state.

In this simplified example, we use the validation result just to display a message, and always show a new SimpleCaptcha. In most real use cases, you will only show a new SimpleCaptcha if the user didn't solve the previous one correctly, and execute the protected code fragment (user registration, comment recording, etc.) if the SimpleCaptcha was solved correctly.

If you redirect the user to a different page upon successful SimpleCaptcha completion, it might be a good idea to set a Session variable with the SimpleCaptcha solving result (for example, Session["IsHuman"] = true;) and check it on those subsequent pages (redirecting back to the SimpleCaptcha page if it's not set). Otherwise, bots could be written to skip the Captcha-protected page and go to those later stage pages directly, bypassing the protection.

Finally, since a new Captcha image is shown on each page load and each Captcha code can only be validated once (regardless of the validation result), the user input should always be cleared after SimpleCaptcha validation.


<?xml version="1.0"?>
  For more information on how to configure your ASP.NET application, please 
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
      <!-- Register the HttpHandler used for BotDetect Simple API requests -->
      <add verb="GET" path="BotDetectCaptcha.ashx" 
      type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
    <pages controlRenderingCompatibilityVersion="4.5">
      <!-- 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=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    <machineKey compatibilityMode="Framework45"/>
    <validation validateIntegratedModeConfiguration="false"/>
      <!-- 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"/>

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


<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="" 



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 .