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

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/vbnet/ folder; and contains the following files:

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>
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
</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: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>
        <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.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 Captcha howto guide, form submission processing 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 Not 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.

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.0" 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 helpLinkEnabled="true" helpLinkMode="image"/>
</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.