ASP.NET Basic CAPTCHA C# Code Example

First Time Here?

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

The ASP.NET Basic Captcha 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 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/csharp/ folder; and contains the following files:


<%@ 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>
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
  <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:WebFormsCaptcha runat="server" ID="ExampleCaptcha"
      UserInputID="CaptchaCodeTextBox" />
      <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 Captcha howto guide, the <BotDetect:Captcha> custom web control generates the Html markup required to show the Captcha image and the Captcha 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 Captcha 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 Captcha howto guide, form submission processing is done in the Page_PreRender event handler, so all individual control events are executed before the Captcha validation. If you want to validate the user's Captcha input before individual control events, you can also place the Captcha 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 Captcha 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 Captcha regardless of other form submission variables ensures proper Captcha security in all cases.

Form Setup Code

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

On each page load, we register the <asp:TextBox> control ClientID with the Captcha control instance. This allows the BotDetect client-side scripts to process the user's Captcha code input (such as automatically lowercasing it to signal that Captcha codes are not case-sensitive, automatically clearing previous user input on Reload button clicks, etc.)

Captcha Validation Code

When the page is submitted (if (IsPostBack)), we forward the user input to the Captcha.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 Captcha. In most real use cases, you will only show a new Captcha if the user didn't solve the previous one correctly, and execute the protected code fragment (user registration, comment recording, etc.) if the Captcha was solved correctly.

If you redirect the user to a different page upon successful Captcha completion, it might be a good idea to set a Session variable with the Captcha solving result (for example, Session["IsHuman"] = true;) and check it on those subsequent pages (redirecting back to the Captcha 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 Captcha validation.


<?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=, 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.