ASP.NET Basic CAPTCHA C# Code Sample (BotDetect v3.0; deprecated)

First Time Here?

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

The ASP.NET Basic Captcha sample 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.

Visual Studio 2013 / Visual Studio 2012 / .NET 4.5

By default, the .NET 4.5 C# version of the ASP.NET Basic Captcha sample project is installed at:
C:\Program Files\Lanapsoft\BotDetect 3 CAPTCHA Component\Asp.Net\v4.5\WebApp\AspNetBasicCaptchaSample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Lanapsoft > BotDetect 3 CAPTCHA Component > ASP.NET > DotNET 4.5 Web Applications > Run

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 Basic ASP.NET Sample</title>
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
</head>
<body>
  <form id="form1" runat="server">
  <h1>BotDetect CAPTCHA Basic ASP.NET Sample</h1>
  <fieldset>
    <legend>CAPTCHA Validation</legend>
    <p class="prompt">
      <label for="CaptchaCodeTextBox">Retype the characters from the picture:</label>
    </p>
    <BotDetect:Captcha ID="SampleCaptcha" runat="server" />
    <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>
      <asp:Label ID="CaptchaIncorrectLabel" runat="server" CssClass="incorrect">
      </asp:Label>
    </div>
  </fieldset>
  </form>
</body>
</html>

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.

Default.aspx.cs

using System;
using System.Web;
using System.Web.Security;
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;
        }

        // setup client-side input processing
        SampleCaptcha.UserInputClientID = CaptchaCodeTextBox.ClientID;

        if (IsPostBack)
        {
            // validate the Captcha to check we're not dealing with a 
            bot
            string code = CaptchaCodeTextBox.Text.Trim().ToUpper();
            bool isHuman = SampleCaptcha.Validate(code);
            CaptchaCodeTextBox.Text = null; // clear previous user 
            input

            if (isHuman)
            {
                CaptchaCorrectLabel.Visible = true;
                CaptchaIncorrectLabel.Visible = false;
            }
            else
            {
                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 sample, 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.

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>
  <configSections>
    <section name="botDetect" requirePermission="false" 
      type="BotDetect.Configuration.BotDetectConfigurationSection, BotDetect"/>
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
  </appSettings>
  <system.web>
    <httpHandlers>
      <!-- Register the HttpHandler used for BotDetect Captcha requests -->
      <add verb="GET" path="BotDetectCaptcha.ashx" 
        type="BotDetect.Web.CaptchaHandler, BotDetect"/>
    </httpHandlers>
    <!-- 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">
      <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 Captcha requests (IIS 7.0+) -->
      <remove name="BotDetectCaptchaHandler"/>
      <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" 
        path="BotDetectCaptcha.ashx" type="BotDetect.Web.CaptchaHandler, BotDetect"/>
    </handlers>
  </system.webServer>
  <botDetect>
    <captchaImage>
      <helpLink enabled="true" mode="image" />
    </captchaImage>
  </botDetect>
</configuration>

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.

Visual Studio 2010 / .NET 4.0

By default, the .NET 4.0 C# version of the ASP.NET Basic Captcha sample project is installed at:
C:\Program Files\Lanapsoft\BotDetect 3 CAPTCHA Component\Asp.Net\v4.0\WebApp\AspNetBasicCaptchaSample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Lanapsoft > BotDetect 3 CAPTCHA Component > ASP.NET > DotNET 4.0 Web Applications > Run

The Visual Studio 2010 / .NET 4.0 source has no essential differences from the Visual Studio 2013 / Visual Studio 2012 / .NET 4.5 source.

Visual Studio 2008 / .NET 3.5

By default, the .NET 3.5 C# version of the ASP.NET Basic Captcha sample project is installed at:
C:\Program Files\Lanapsoft\BotDetect 3 CAPTCHA Component\Asp.Net\v3.5\WebApp\AspNetBasicCaptchaSample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Lanapsoft > BotDetect 3 CAPTCHA Component > ASP.NET > DotNET 3.5 Web Applications > Run

The Visual Studio 2008 / .NET 3.5 source has no essential differences from the Visual Studio 2013 / Visual Studio 2012 / .NET 4.5 source.

Visual Studio 2005 / .NET 2.0

By default, the .NET 2.0 C# version of the ASP.NET Basic Captcha sample project is installed at:
C:\Program Files\Lanapsoft\BotDetect 3 CAPTCHA Component\Asp.Net\v2.0\WebApp\AspNetBasicCaptchaSample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Lanapsoft > BotDetect 3 CAPTCHA Component > ASP.NET > DotNET 2.0 Web Applications > Run

The Visual Studio 2005 / .NET 2.0 source has no essential differences from the Visual Studio 2013 / Visual Studio 2012 / .NET 4.5 source.


Please Note

The information on this page is out of date and applies to a deprecated version of BotDetect™ CAPTCHA (v3.0).

An up-to-date equivalent page for the latest BotDetect Captcha release (v4) is BotDetect v4 Captcha documentation index.

General information about the major improvements in the current BotDetect release can be found at the What's New in BotDetect v4.0 page.