ASP.NET CAPTCHA Application Config Settings C# Code Example

The ASP.NET Captcha application config settings example project shows how to configure BotDetect CAPTCHA challenges by overriding Captcha control defaults in application configuration files.

First Time Here?

Check the BotDetect Developer Crash Course for key integration steps.

BotDetect allows user-defined customization of many Captcha options through a special <botDetect> section of the web.config file.

Captcha settings from this configuration file will apply to all Captcha challenges shown on forms in the applications, and will act as defaults with which all Captcha objects will be created. This makes configuration file settings the simplest and most convenient way of Captcha customization for most use cases.

The web.config file file used in this code example contains detailed descriptions and explanations of the many customizable Captcha options exposed by the BotDetect ASP.NET Captcha configuration API.

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

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 Captcha application config settings example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET4.5\WebApp\CaptchaApplicationConfigSettingsExample\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>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>BotDetect ASP.NET CAPTCHA Options: Application Config Settings Code 
  Example</title>
  <link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
  <script type="text/javascript" 
  src="<%= BotDetect.Web.CaptchaUrls.ScriptIncludeUrl %>"></script>
</head>
<body>
  <form runat="server" class="column" id="form1">
    <h1>BotDetect ASP.NET CAPTCHA Options:
      <br />
      Application Config Settings 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" 
      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" 
        CssClass="incorrect"></asp:Label>
      </div>
    </fieldset>
  </form>
</body>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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;
    }

    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;
      }
      else
      {
        CaptchaCorrectLabel.Visible = false;
        CaptchaIncorrectLabel.Visible = true;
      }
    }
  }
}

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="CaptchaCustomPath.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.5" 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="CaptchaCustomPath.ashx" 
    type="BotDetect.Web.CaptchaHandler, BotDetect"/>
  </handlers>
  </system.webServer>
  <botDetect
    codeLength="3-5"
    codeStyle="alpha"
    disallowedCodeSubstrings="d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa,
    bb,cc,abc,bca,cab"
    codeTimeout="600"
    testModeEnabled="false"
    imageStyle="Chipped,Fingerprints,Graffiti,Bullets"
    imageWidth="200"
    imageHeight="50"
    imageFormat="png"
    customDarkColor="#483d8b"
    customLightColor="#87cefa"
    disabledImageStyles="Chipped,Lego,Wave"
    soundEnabled="true"
    soundStyle="Dispatch,RedAlert,Synth"
    soundFormat="WavPcm16bit8kHzMono"
    soundRegenerationMode="None"
    soundPackagesFolder="C:\Program Files (x86)\Captcha Inc\BotDetect 4 CAPTCHA 
    Component\Asp.Net\BotDetectSounds"
    warnAboutMissingSoundPackages="false"
    disabledSoundStyles="RedAlert,HiveMind"
    locale="en-US"
    imageTooltip="Custom Captcha image tooltip"
    soundTooltip="Custom Captcha sound icon tooltip"
    reloadTooltip="Custom Captcha reload icon tooltip"
    helpLinkText="Custom Captcha help link text"
    helpLinkUrl="custom-captcha-help-page.html"
    reloadEnabled="false"
    useSmallIcons="false"
    useHorizontalIcons="false"
    soundIconUrl="~/custom-sound-icon.gif"
    reloadIconUrl=""
    iconsDivWidth="25"
    helpLinkEnabled="true"
    helpLinkMode="text"
    additionalCssClasses="class1 class2 class3"
    additionalInlineCss="border: 4px solid #fff; background-color: #f8f8f8;"
    addScriptInclude="false"
    addInitScript="true"
    autoUppercaseInput="true"
    autoFocusInput="true"
    autoClearInput="true"
    autoReloadExpiredCaptchas="true"
    autoReloadTimeout="3600"
    soundStartDelay="1000"
    remoteScriptEnabled="false"
    httpHandlerRequestPath="CaptchaCustomPath.ashx"
    httpHandlerTroubleshootingEnabled="true"
    requestFilterEnabled="true"
    requestFilterRepeatedRequestsAllowed="10"
    sessionTroubleshootingEnabled="true"
    sessionIdEncryptionPassword="SecretEncryptionPassword"
    loggingProvider="BotDetect.Logging.NullLoggingProvider, BotDetect"
    errorLoggingEnabled="true"
    traceLoggingEnabled="true"
    traceLoggingEventFilter="Initialized"
  />
</configuration>

Visual Studio 2010 / .NET 4.0

By default, the .NET 4.0 C# version of the ASP.NET Captcha Application Config Settings example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET4.0\WebApp\CaptchaApplicationConfigSettingsExample\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.

Visual Studio 2008 / .NET 3.5

By default, the .NET 3.5 C# version of the ASP.NET Captcha Application Config Settings example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET3.5\WebApp\CaptchaApplicationConfigSettingsExample\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.

Visual Studio 2005 / .NET 2.0

By default, the .NET 2.0 C# version of the ASP.NET Captcha Application Config Settings example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET2.0\WebApp\CaptchaApplicationConfigSettingsExample\CSharp

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 CAPTCHA Component > ASP.NET > DotNET 2.0 Web Applications > Run

The Visual Studio 2005 / .NET 2.0 source has no essential differences from the Visual Studio 2013 / Visual Studio 2012 / .NET 4.5 source.