ASP.NET Ajax CAPTCHA C# Code Example

The ASP.NET Ajax Captcha example project shows how to use BotDetect CAPTCHA within an ASP.NET Ajax UpdatePanel. The basic code used to add Captcha protection to the page is the same as in regular ASP.NET forms.

First Time Here?

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

However, some additional work is required if BotDetect is not visible on the first page load, but gets added to the page dynamically. Since BotDetect can't automatically add required stylesheet and client-side script includes to the page if it's not visible on the first page load, they can be added manually.

In this example, the BotDetect stylesheet include is added to the Default.aspx page header, while the script include and the BotDetect initialization script are registered in the code-behind.

Download the BotDetect ASP.NET CAPTCHA Component and run this example

ASP.NET Ajax 4.5 / Visual Studio 2015 / Visual Studio 2013 / Visual Studio 2012 / .NET 4.6 / .NET 4.5

By default, the .NET 4.5 C# version of the ASP.NET Ajax Captcha example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET4.5\WebApp\AspNetWebFormsAjaxCaptchaExample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 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 ASP.NET Ajax Example</title>
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
  <!-- ensure the BotDetect layout stylesheet is included -->
  <link type="text/css" rel="Stylesheet" href="BotDetectCaptcha.ashx?get=layoutStylesheet" />
</head>
<body>
  <form id="form1" runat="server">
    <h1>BotDetect CAPTCHA ASP.NET Ajax Example</h1>
    <fieldset>
      <legend>CAPTCHA Validation</legend>
      <asp:ScriptManager ID="ScriptManager1" runat="server" />
      <asp:UpdatePanel ID="CaptchaUpdatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
          <asp:Panel ID="Panel1" runat="server">
            <h3>Step 1</h3>
            <p class="prompt">The first screen doesn't contain BotDetect yet. 
            After you click "Next", Captcha protection will be shown using an 
            ASP.NET Ajax partial postback.</p>
            <asp:Button ID="Button1" runat="server" Text="Next" OnClick="Button1_Click" />
          </asp:Panel>
          <asp:Panel ID="Panel2" runat="server" Visible="false">
            <h3>Step 2</h3>
            <p class="prompt">
              <label for="CaptchaCodeTextBox">Retype the characters from the 
              picture:</label>
            </p>
            <BotDetect:WebFormsCaptcha ID="ExampleCaptcha" runat="server" />
            <div class="validationDiv">
              <asp:TextBox ID="CaptchaCodeTextBox" runat="server"></asp:TextBox>
              <asp:Button ID="ValidateCaptchaButton" runat="server" 
              OnClick="ValidateCaptchaButton_Click" />
              <asp:Label ID="CaptchaIncorrectLabel" runat="server" 
              CssClass="incorrect"></asp:Label>
            </div>
          </asp:Panel>
        </ContentTemplate>
      </asp:UpdatePanel>
    </fieldset>
  </form>
</body>
</html>

To showcase the most complex ASP.NET Ajax workflow, BotDetect is added to a Panel within an UpdatePanel, and added to the form dynamically after an ASP.NET Ajax partial postback.

Since BotDetect wasn't visible on the page during the first load, it couldn't add the Captcha stylesheet and script library to the page. Adding them during the partial page update doesn't always work, so we also included the BotDetect stylesheet in the page header.

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_Load(object sender, EventArgs e)
  {
    // initial page setup
    if (!IsPostBack)
    {
      // set control text
      ValidateCaptchaButton.Text = "Validate";
      CaptchaIncorrectLabel.Text = "Incorrect!";
    }

    // setup client-side input processing
    ExampleCaptcha.UserInputID = CaptchaCodeTextBox.ClientID;
  }

  protected void Button1_Click(object sender, EventArgs e)
  {
    Panel1.Visible = false;
    Panel2.Visible = true;

    CaptchaIncorrectLabel.Visible = false;

    // ensure the BotDetect client scripts are added to the page
    IncludeBotDetectScripts();
  }

  protected void IncludeBotDetectScripts()
  {
    ScriptManager.RegisterClientScriptInclude(
        this.Page,
        this.GetType(),
        "BotDetect_Include",
        ExampleCaptcha.WebCaptcha.UrlGenerator.ScriptIncludeUrl);

    ScriptManager.RegisterClientScriptBlock(
        this.Page,
        this.GetType(),
        "BotDetect_Init",
        ExampleCaptcha.WebCaptcha.InitScriptMarkup,
        false);
  }

  protected void ValidateCaptchaButton_Click(object sender, EventArgs e)
  {
    // validate the Captcha to check we're not dealing with a bot
    string code = CaptchaCodeTextBox.Text.Trim().ToUpper();
    bool isHuman = ExampleCaptcha.Validate(code);
    CaptchaCodeTextBox.Text = null; // clear previous user input

    if (isHuman)
    {
      CaptchaIncorrectLabel.Visible = false;

      Panel1.Visible = true;
      Panel2.Visible = false;
    }
    else
    {
      CaptchaIncorrectLabel.Visible = true;
    }
  }
}

To ensure BotDetect client-side scripts are added to the page when they are needed, we call the IncludeBotDetectScripts() helper before the second panel becomes visible. The rest of the class contains the usual BotDetect setup and validation code, adjusted for the two-panel workflow.

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 enableSessionState="true" controlRenderingCompatibilityVersion="4.5">
    <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" 
  encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  <trace enabled="false" localOnly="true"/>
  <httpCookies httpOnlyCookies="true"/>
  <trust level="Medium" originUrl=""/>
  <authentication mode="None"/>
  <customErrors mode="RemoteOnly"/>
</system.web>
<system.webServer>
  <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>
  <validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
</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.

ASP.NET Ajax 4.0 / Visual Studio 2010 / .NET 4.0

By default, the .NET 4.0 C# version of the ASP.NET Ajax Captcha example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET4.0\WebApp\AspNetAjax40CaptchaExample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 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.

ASP.NET Ajax 1.0 / Visual Studio 2008 / .NET 3.5

By default, the .NET 3.5 C# version of the ASP.NET Ajax Captcha example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\v3.5\WebApp\AspNetAjax10CaptchaExample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 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.