ASP.NET WebForms Application Template CAPTCHA VB.NET Code Example

First Time Here?

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

The ASP.NET WebForms application template Captcha example project shows how to add BotDetect CAPTCHA protection to the registration form included in the default ASP.NET Web Forms Application project template coming with Visual Studio.

The example shows how to include BotDetect CAPTCHA validation in new user data validation for the example Register form

The example also shows how to complement server-side CAPTCHA validation with client-side Ajax CAPTCHA validation using ASP.NET unobtrusive validation applied to all form fields.

Download the BotDetect ASP.NET CAPTCHA Generator archive to run this example
  • C#
  • VB.NET

Visual Studio 2015 / Visual Studio 2013 / .NET 4.6 / .NET 4.5.1

The Visual Studio 2015 / 2013 WebForms application Captcha example project shows how to add BotDetect CAPTCHA protection to the registration form included in the default ASP.NET Web Forms Application project template coming with Visual Studio 2015 / 2013 (File > New Project > Installed > Templates > Visual C# > Web > ASP.NET Web Application > Web Forms).

Since the Register form uses ASP.NET Identity user management, the example shows how to include BotDetect CAPTCHA validation in new user data validation (see Account/Register.aspx and Account/Register.aspx.cs source code).

The example also shows how to complement server-side CAPTCHA validation with client-side Ajax CAPTCHA validation using ASP.NET 4.6 / 4.5.1 unobtrusive validation applied to all form fields (Scripts/WebForms/WebUICaptchaValidation.js).

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

Example Code Files


<%@ Page Title="Register" Language="vb" AutoEventWireup="false" 
MasterPageFile="~/Site.Master" CodeBehind="Register.aspx.vb" 
Inherits="AspNetWebForms451CaptchaExampleVBNet.Register" %>

<%@ Import Namespace="BotDetect.Web.UI" %>

<%@ Import Namespace="AspNetWebForms451CaptchaExampleVBNet" %>
<%@ Import Namespace="Microsoft.AspNet.Identity" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
  <h2><%: Title %>.</h2>
  <p class="text-danger">
    <asp:Literal runat="server" ID="ErrorMessage" />

  <div class="form-horizontal">
    <h4>Create a new account.</h4>
    <hr />

    <div class="col-md-6" id="form-container">

      <asp:ValidationSummary runat="server" CssClass="text-danger" />

      <div class="form-group">
        <asp:Label runat="server" AssociatedControlID="UserNameCtrl" 
        CssClass="col-md-4 control-label">User name</asp:Label>
        <div class="col-md-8">
          <asp:TextBox runat="server" ID="UserNameCtrl" CssClass="form-control" />
          <asp:RequiredFieldValidator runat="server" 
            CssClass="text-danger" ErrorMessage="The user name field is required. " />
      <div class="form-group">
        <asp:Label runat="server" AssociatedControlID="Password" CssClass="col-md-4 control-label">Password</asp:Label>
        <div class="col-md-8">
          <asp:TextBox runat="server" ID="Password" TextMode="Password" 
          CssClass="form-control" />
          <asp:RequiredFieldValidator runat="server" 
            CssClass="text-danger" ErrorMessage="The password field is required." />
      <div class="form-group">
        <asp:Label runat="server" AssociatedControlID="ConfirmPassword" 
        CssClass="col-md-4 control-label">Confirm password</asp:Label>
        <div class="col-md-8">
          <asp:TextBox runat="server" ID="ConfirmPassword" TextMode="Password" 
          CssClass="form-control" />
          <asp:RequiredFieldValidator runat="server" 
            CssClass="text-danger" Display="Dynamic" 
            ErrorMessage="The confirm password field is required." />
          <asp:CompareValidator runat="server" ControlToCompare="Password" 
            CssClass="text-danger" Display="Dynamic" 
            ErrorMessage="The password and confirmation password do not match." />
      <!-- Add the controls for CAPTCHA validation to the registration form -->
      <div class="form-group">
        <div class="col-md-offset-4 col-md-8">
          <BotDetect:WebFormsCaptcha ID="RegisterCaptcha" runat="server" />
        <asp:Label runat="server" AssociatedControlID="CaptchaCode" 
        CssClass="col-md-4 control-label">Retype code</asp:Label>
        <div class="col-md-8">
          <asp:TextBox runat="server" ID="CaptchaCode" CssClass="form-control 
          captchaVal" />
          <asp:RequiredFieldValidator ID="CaptchaRequiredValidator" 
          runat="server" ControlToValidate="CaptchaCode"
            CssClass="text-danger" Display="Dynamic" 
            ErrorMessage="Retyping the code from the picture is required." />
          <asp:CustomValidator runat="server" ID="CaptchaValidator" 
            CssClass="text-danger" Display="Dynamic" 
            ErrorMessage="Incorrect code, please try again."
            ClientValidationFunction="ValidateCaptcha" />
      <div class="form-group" id="form-submit">
        <div class="col-md-offset-4 col-md-8">
          <asp:Button runat="server" OnClick="CreateUser_Click" Text="Register" 
          CssClass="btn btn-default" />

To show a Captcha test on the registration form, we add a <BotDetect:Captcha> control and a textbox in which the visitor will type the displayed Captcha code. We also tag this textbox with a special CSS class (captchaVal), so we can attach client-side jQuery validation to it dynamically without knowing its exact ID.

To make the Captcha code a required form field, we add a <asp:RequiredFieldValidator>. For proper Captcha validation comparing the user input to the Captcha code stored on the server during image generation, we add a <asp:CustomValidator> associated with the textbox and set its OnServerValidate property to point to a validation function in form code-behind. To allow unobtrusive Ajax Captcha validation, we set its ClientValidationFunction to point at the custom Ajax Captcha validation script we will define in client-side code.


Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports System
Imports System.Linq
Imports System.Web
Imports System.Web.UI

Partial Public Class Register
  Inherits Page

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles 
    ' setup client-side input processing
    RegisterCaptcha.UserInputID = CaptchaCode.ClientID
  End Sub

  Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
    If Me.IsValid Then
      Dim userName As String = UserNameCtrl.Text
      Dim manager = New UserManager()
      Dim user = New ApplicationUser() With {.UserName = userName}
      Dim result = manager.Create(user, Password.Text)
      If result.Succeeded Then
        IdentityHelper.SignIn(manager, user, isPersistent:=False)
        ErrorMessage.Text = result.Errors.FirstOrDefault()
      End If
    End If

  End Sub

  Protected Sub CaptchaValidator_ServerValidate(source As Object, args As 
    ' validate the Captcha to check we're not dealing with a bot
    args.IsValid = RegisterCaptcha.Validate(args.Value.Trim())

    CaptchaCode.Text = Nothing ' clear previous user input
  End Sub
End Class

In the Page_Load event handler, we set the UserInputID property of the Captcha control required for client-side Captcha object initialization. This is needed because the custom client-side Ajax Captcha validation code will require that object instance to work.

In the CaptchaValidator_ServerValidate function registered to handle server-side validation of the <asp:CustomValidator>, we use the Captcha control's Validate() method to check user input. We also clear the Captcha code textbox after validation, since each Captcha code can only be validated once for security reasons.


// CAPTCHA client-side validation function
function ValidateCaptcha(source, arguments) {
  var captcha = $(".captchaVal").get(0).Captcha;
  var validationUrl = captcha.ValidationUrl + "&i=" + arguments.Value;
  $.getJSON(validationUrl, function (data) {
    // WebUIValidation.js status update
    source.isvalid = data;

    // reload the Captcha image if validation failed
    if (!data) { captcha.ReloadImage(); }

In this file, we extend the unobtrusive client-side WebForms validation with a simple Captcha validation function.

To access the client-side Captcha object, we read it from the Captcha property of the textbox marked with the captchaVal CSS class. We can then get the ValidationUrl pointing to the BotDetect HttpHandler endpoint used for Ajax Captcha validation, append the user input as an additional &i= querystring parameter, and start the Ajax validation call using the jQuery $.getJSON() function.

When the Ajax call returns the JSON-encoded Captcha validation result, we forward it to unobtrusive client-side WebForms validation code that updates ASP.NET validator status and display. We also reload the Captcha image immediately if validation failed, since the code it is showing will have been invalidated in that case, and can't be used anymore.


Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Optimization

Public Class BundleConfig
  ' For more information on Bundling, visit
  Public Shared Sub RegisterBundles(ByVal bundles As BundleCollection)
    bundles.Add(New ScriptBundle("~/bundles/WebFormsJs").Include(

    ' Order is very important for these files to work, they have explicit 
    bundles.Add(New ScriptBundle("~/bundles/MsAjaxJs").Include(

    ' Use the Development version of Modernizr to develop with and learn from. 
    Then, when you’re
    ' ready for production, use the build tool at to pick 
    only the tests you need
    bundles.Add(New ScriptBundle("~/bundles/modernizr").Include(
    ScriptManager.ScriptResourceMapping.AddDefinition("respond", New 
    ScriptResourceDefinition() With {
            .Path = "~/Scripts/respond.min.js",
            .DebugPath = "~/Scripts/respond.js"})

  End Sub
End Class

To make ASP.NET WebForms unobtrusive validation load the Captcha Ajax validation function, we have to add it to the /bundles/WebFormsJs script bundle.


<?xml version="1.0" encoding="utf-8"?>
  For more information on how to configure your ASP.NET application, please 
  <!-- For more information on Entity Framework configuration, visit http://go. -->
  <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.
  EntityFrameworkSection, EntityFramework, Version=, Culture=neutral, 
  PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <section name="botDetect" requirePermission="false" type="BotDetect.
  Configuration.BotDetectConfigurationSection, BotDetect"/>
  <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;
  20140226081704.mdf;Initial Catalog=aspnet-AspNetWebForms451CaptchaExampleVBNet-
  20140226081704;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  <!--<add key="owin:AutomaticAppStartup" value="false" />-->

  <authentication mode="None" />
  <compilation debug="false" strict="false" explicit="true" targetFramework="4.5.
  1" />
  <httpRuntime targetFramework="4.5.1" />
    <add namespace="System.Web.Optimization" />
    <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" 
    namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
    <!-- Register the BotDetect tag prefix for easier use in all pages -->
    <add assembly="BotDetect" namespace="BotDetect.Web.UI" 
        ASP.NET Membership is disabled in this template. Please visit the 
        following link to learn 
        about the ASP.NET Membership support in this template
    <clear />
        ASP.NET Membership Profile is disabled in this template. Please visit 
        the following link to 
        learn about the ASP.NET Membership support in this template
    <clear />
          ASP.NET Membership Role is disabled in this template. Please visit the 
          following link to learn 
          about the ASP.NET Membership support in this template
    <clear />
            If you are deploying to a cloud environment that has multiple web 
            server instances,
            you should change session state mode from "InProc" to "Custom". In 
            change the connection string named "DefaultConnection" to connect to 
            an instance
            of SQL Server (including SQL Azure and SQL  Compact) instead of to 
            SQL Server Express.
    <!-- 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" customProvider="DefaultSessionProvider" 
  sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect">
    <add name="DefaultSessionProvider" type="System.Web.Providers.
    DefaultSessionStateProvider, System.Web.Providers, Version=, 
    Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
    connectionStringName="DefaultConnection" />
  <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"/>
    <remove name="FormsAuthenticationModule" />
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="" newVersion=""/>
    <assemblyIdentity name="EntityFramework" culture="neutral" 
    publicKeyToken="b77a5c561934e089" />
    <bindingRedirect oldVersion="" newVersion="" />
  type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameter value="v11.0" />
    <provider invariantName="System.Data.SqlClient" 
    type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
  <botDetect helpLinkEnabled="true" helpLinkMode="image" />

To allow the application to use BotDetect Captcha protection, we must enable and configure sessionState (required for BotDetect), and register the BotDetect HttpHandler in both <system.web><httpHandlers> and <system.webServer><handlers> configuration sections.