ASP.NET Basic CAPTCHA VB.NET 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
  • C#
  • VB.NET

Visual Studio 2005-2017 / .NET 2.0 and onwards

By default, the VB.NET version of 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\VBNet

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="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" 
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 ASP.NET CAPTCHA Validation: Basic ASP.NET WebForms CAPTCHA 
  Code Example</title>

</head>
<body>
  <form runat="server" class="column" id="form1">
    <h1>BotDetect ASP.NET CAPTCHA Validation:
      <br />
      Basic ASP.NET WebForms CAPTCHA Code Example</h1>
    <fieldset>
      <legend>ASP.NET WebForm CAPTCHA Validation</legend>
      <p class="prompt">
        <label for="CaptchaCodeTextBox">Retype the characters from the picture:</label></p>
      <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>
        <asp:Label ID="CaptchaIncorrectLabel" runat="server" 
        CssClass="incorrect"></asp:Label>
      </div>
    </fieldset>
  </form>
</body>
</html>

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.

Default.aspx.vb

Partial Class _Default
  Inherits System.Web.UI.Page

  Protected Sub Page_PreRender(ByVal sender As Object, 
    ByVal e As System.EventArgs) Handles Me.PreRender
    ' initial page setup
    If Not IsPostBack Then
      ' 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
    End If

    If IsPostBack Then
      ' validate the Captcha to check we're not dealing with a bot
      Dim isHuman As Boolean
      isHuman = ExampleCaptcha.Validate()
      If isHuman Then
        CaptchaCorrectLabel.Visible = True
        CaptchaIncorrectLabel.Visible = False
      Else
        CaptchaCorrectLabel.Visible = False
        CaptchaIncorrectLabel.Visible = True
      End If
    End If
  End Sub

End Class



Placing the Form Processing Code

As explained in the ASP.NET WebForms SimpleCaptcha howto guide, form submission processing 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 Not 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.

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.0">
      <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 and 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>CaptchaCodeTextBox</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 .