ASP.NET CAPTCHA Troubleshooting C# Code Example

The ASP.NET Captcha troubleshooting example project shows how to use BotDetect CAPTCHA built-in error logging and Captcha event tracing, using the BotDetect Troubleshooting utility based on log4net.

First Time Here?

Check the BotDetect Developer Crash Course for key integration steps.

The logging requires the <captchaLogging> element and BotDetectTroubleshooting Module registration in the web.config file, as well as the log4net.config file defining log4net settings (in this case, logging to simple text files).

Such logging techniques can be used as a foundation for effective diagnosis and resolution of any BotDetect issues you might encounter on your servers.

The example demonstrates the effects of following the How To Troubleshoot BotDetect ASP.NET CAPTCHA Issues guide.

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

Visual Studio 2005-2017 / .NET 2.0 and onwards

By default, the .NET C# version of the ASP.NET Captcha troubleshooting example project is installed at:
C:\Program Files\Captcha Inc\BotDetect CAPTCHA\aspnetlegacy+netlegacy\Examples\TraditionalAPI\CaptchaTroubleshootingExample\ CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect CAPTCHA > ASPNETLEGACY + NETLEGACY Examples > Legacy ASP.NET + Legacy .NET Run code examples


<<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
Inherits="_Default" %> 

<!DOCTYPE html> 

<html xmlns=""> 
<head id="Head1" runat="server"> 
  <title>BotDetect ASP.NET CAPTCHA Options: Troubleshooting Helper Code Example</title> 
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" /> 
  <form id="form1" class="column" runat="server"> 
    <h1>BotDetect ASP.NET CAPTCHA Options:<br /> 
      Troubleshooting Helper Code Example</h1> 
    <fieldset id="TroubleshootingDebug"> 
      <legend>CAPTCHA Debug Logging</legend> 
      <p class="prompt"> 
        <label for="CaptchaCodeTextBox">Retype the characters from the picture:</label></p> 
      <BotDetect:WebFormsCaptcha runat="server" ID="ExampleCaptcha" 
      UserInputControlID="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" 
      <p class="validationTroubleshooting">A detailed trace of all CAPTCHA 
      events will be logged to the <code>debug.txt</code> file in the example 
      <div class="troubleshooting"> 
        <asp:Label ID="DebugLabel" runat="server"></asp:Label> 
    <fieldset id="TroubleshootingError"> 
      <legend>CAPTCHA Error Logging</legend> 
      <p class="troubleshooting">Clicking <em>Simulate Error</em> will throw a 
      fake BotDetect CAPTCHA exception and log it to the <code>error.txt</code> 
      file in the example folder.</p> 
      <asp:Button ID="CauseErrorButton" runat="server" 
      OnClick="CauseErrorButton_Click" /> 
      <div class="troubleshooting"> 
        <asp:Label ID="ErrorLabel" runat="server"></asp:Label> 


using System; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

using BotDetect; 
using BotDetect.Web; 
using BotDetect.Web.UI; 

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; 

      CauseErrorButton.Text = "Simulate error"; 
      ErrorLabel.Text = "An error has been generated. Please check the 'error.txt' file."; 

      DebugLabel.Text = "A validation attempt has been logged. Please check the 'debug.txt' file."; 
      DebugLabel.Visible = false; 

    if (null != Session["error"]) 
      ErrorLabel.Visible = true; 
      CaptchaCorrectLabel.Visible = false; 
      CaptchaIncorrectLabel.Visible = false; 
      Session["error"] = null; 
      DebugLabel.Visible = false; 
      ErrorLabel.Visible = false; 

    if (IsPostBack) 
      // validate the Captcha to check we're not dealing with a bot 
      bool isHuman = ExampleCaptcha.Validate(); 
      if (isHuman) 
        CaptchaCorrectLabel.Visible = true; 
        CaptchaIncorrectLabel.Visible = false; 
        CaptchaCorrectLabel.Visible = false; 
        CaptchaIncorrectLabel.Visible = true; 

      DebugLabel.Visible = true; 

  protected void CauseErrorButton_Click(object sender, EventArgs e) 
    Session["error"] = true; 
    throw new BotDetect.WebCaptchaException("Simulated exception"); 


<%@ Application Language="C#" %> 

<script RunAt="server"> 

  void Application_Start(object sender, EventArgs e) 
    // Code that runs on application startup 


  void Application_End(object sender, EventArgs e) 
    //  Code that runs on application shutdown 


  void Application_Error(object sender, EventArgs e) 
    // Code that runs when an unhandled error occurs 

    // since we log the errors using our handler,  
    // they don't need to be shown to the client 


  void Session_Start(object sender, EventArgs e) 
    // Code that runs when a new session is started 


  void Session_End(object sender, EventArgs e) 
    // Code that runs when a session ends.  

    // Note: The Session_End event is raised only when the sessionstate mode 
    // is set to InProc in the Web.config file. If session mode is set to  
    // StateServer  
    // or SQLServer, the event is not raised. 



<?xml version="1.0"?> 

<!-- This section contains the log4net configuration settings --> 
<log4net debug="false"> 

  <!-- Errors are logged to a 'error.txt' file --> 
  <appender name="ErrorFileAppender" type="log4net.Appender.FileAppender"> 
  <file value="error.txt" /> 
  <appendToFile value="true" /> 
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> 
  <layout type="log4net.Layout.PatternLayout,log4net"> 
    <conversionPattern value="%date [%thread] %type - %n%n%message%n%n" /> 

  <!-- Error logging is enabled, comment-out to disable --> 
  <logger name="ErrorLogger"> 
  <level value="ERROR" /> 
  <appender-ref ref="ErrorFileAppender" /> 

  <!-- Debug info is logged to a 'debug.txt' file --> 
  <appender name="DebugFileAppender" type="log4net.Appender.FileAppender"> 
  <file value="debug.txt" /> 
  <appendToFile value="true" /> 
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> 
  <layout type="log4net.Layout.PatternLayout,log4net"> 
    <conversionPattern value="%date [%thread] %type - %n%n%message%n%n" /> 

  <!-- Debug logging is enabled, comment-out to disable --> 
  <logger name="DebugLogger"> 
  <level value="DEBUG" /> 
  <appender-ref ref="DebugFileAppender" /> 



<?xml version="1.0"?> 
  For more information on how to configure your ASP.NET application, please  
    <!-- Register the log4net configuration section --> 
    <section name="log4net" 
    type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" 
    <!-- Register the BotDetect configuration section --> 
    <section name="botDetect" 
    type="BotDetect.Configuration.BotDetectConfigurationSection, BotDetect" requirePermission="false"/> 
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> 
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> 
  <!-- log4net settings are loaded from a separate config file --> 
  <log4net configSource="log4net.config"/> 
  <!-- Register the log4net BotDetect logging provider --> 
   loggingProvider="BotDetect.Logging.Log4NetLoggingProvider, BotDetect.Troubleshooting" 
      <!-- Register the HttpHandler used for BotDetect Captcha requests --> 
      <add verb="GET" path="BotDetectCaptcha.ashx" 
      type="BotDetect.Web.CaptchaHandler, BotDetect"/> 
      <!-- Register the HttpModule used for BotDetect error logging (IIS 5.0, 5.1,  
      6.0) --> 
      <add name="BotDetectTroubleshootingModule" 
      type="BotDetect.Web.CaptchaTroubleshootingModule, BotDetect"/> 
    <!-- 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"> 
      <!-- Register the BotDetect tag prefix for easier use in all pages --> 
      <add assembly="BotDetect" namespace="BotDetect.Web.UI" 
    <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" /> 
    <trace enabled="false" localOnly="true"/> 
    <httpCookies httpOnlyCookies="true"/> 
    <trust level="Medium" originUrl=""/> 
    <authentication mode="None"/> 
    <customErrors mode="RemoteOnly"/> 
  <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"/> 
    <!-- Register the HttpModule used for BotDetect error logging (IIS 7.0+) --> 
    <remove name="BotDetectTroubleshootingModule"/> 
    <add name="BotDetectTroubleshootingModule" preCondition="integratedMode" 
    type="BotDetect.Web.CaptchaTroubleshootingModule, BotDetect"/>