ASP.NET CAPTCHA Form Object Settings C# Code Example
The ASP.NET Captcha form object settings example project shows how to configure BotDetect CAPTCHA challenges by setting Captcha control properties in ASP.NET form source.
First Time Here?
Check the BotDetect Developer Crash Course for key integration steps.
Multiple ASP.NET forms within the same ASP.NET website can be protected by BotDetect Captcha challenges: e.g. you could add Captcha controls in both your Contact form and Registration form source.
To function properly, separate Captcha challenges placed on each form should have different names (CaptchaId
values, Captcha1
and Captcha2
in this example), and can use completely different Captcha settings.
Even multiple Captcha instances placed on the same form won't interfere with each other's validation and functionality. And if a user opens the same page in multiple browser tabs, each tab will independently validate the shown Captcha code.
Shared Captcha settings should always be placed in the web.config
application configuration file, and only diverging settings set through Captcha object instance properties in form code, to avoid code duplication.
Settings that affect only Captcha container markup generation take effect immediately (changing Captcha.Html
output), but settings that affect Captcha challenge (image or sound) generation in separate Http requests need to be saved in ASP.NET Session state when set through Captcha
object instance properties in form source, consuming server resources and reverting to defaults when the ASP.NET Session expires.
Please note that if configured values are dynamic (e.g. CaptchaRandomization
helper or other function calls in form code), they will be re-calculated only when the form is reloaded (form code is executed). For example, Captcha ImageStyle
randomized in ASP.NET form source will not change on each Captcha Reload button click, but only on each form load.
- C#
- VB.NET
Visual Studio 2005-2017 / .NET 2.0 and onwards
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~conf_via-tag-config/csharp/
folder; and contains the following files:
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: Form Object Settings Code Example</title> <link type="text/css" rel="Stylesheet" href="StyleSheet.css" /> <script type="text/javascript" src="<%= BotDetect.Web.CaptchaUrls.Absolute.ScriptIncludeUrl %>"></script> </head> <body> <form runat="server" class="column" id="form1"> <h1>BotDetect ASP.NET CAPTCHA Options: <br /> Form Object Settings Code Example</h1> <fieldset> <legend>ASP.NET WebForm CAPTCHA Validation</legend> <p class="prompt"> <label for="Captcha1CodeTextBox">Retype the characters from the picture:</label></p> <BotDetect:WebFormsCaptcha runat="server" ID="Captcha1" UserInputID="Captcha1CodeTextBox" CodeLength="6" CodeStyle="Numeric" DisallowedCodeSubstringsCsv="1,2,3,4,5,00,777,9999" CodeTimeout="300" ImageStyle="SunAndWarmAir" ImageSize="250,60" ImageFormat="Png" CustomDarkColor="Black" CustomLightColor="White" SoundEnabled="true" SoundStyle="Synth" SoundFormat="WavPcm8bit8kHzMono" SoundRegenerationMode="Limited" Locale="es-MX" ImageTooltip="Custom Mexican Spanish Captcha image tooltip" SoundTooltip="Custom Mexican Spanish Captcha sound icon tooltip" ReloadTooltip="Custom Mexican Spanish Captcha reload icon tooltip" HelpLinkText="Custom Mexican Spanish Captcha help link text" HelpLinkUrl="custom-mexican-spanish-captcha-help-page.html" ReloadEnabled="true" UseSmallIcons="false" UseHorizontalIcons="false" SoundIconUrl="" ReloadIconUrl="" IconsDivWidth="27" HelpLinkEnabled="true" HelpLinkMode="Text" TabIndex="-1" AdditionalCssClasses="class1 class2 class3" AdditionalInlineCss="border: 4px solid #fff; background-color: #f8f8f8;" AddScriptInclude="true" AddInitScript="true" AutoUppercaseInput="true" AutoFocusInput="true" AutoClearInput="true" AutoReloadExpiredCaptchas="true" AutoReloadTimeout="7200" SoundStartDelay="100" RemoteScriptEnabled="true" /> <div class="validationDiv"> <asp:TextBox ID="Captcha1CodeTextBox" runat="server"></asp:TextBox> <asp:Label ID="Captcha1CorrectLabel" runat="server" CssClass="correct" Text="Correct!" Visible="false"></asp:Label> <asp:Label ID="Captcha1IncorrectLabel" runat="server" CssClass="incorrect" Text="Incorrect!" Visible="false"></asp:Label> </div> </fieldset> <fieldset> <legend>ASP.NET WebForm CAPTCHA Validation</legend> <p class="prompt"> <label for="Captcha2CodeTextBox">Retype the characters from the picture:</label></p> <BotDetect:WebFormsCaptcha runat="server" ID="Captcha2" UserInputID="Captcha2CodeTextBox" /> <div class="validationDiv"> <asp:TextBox ID="Captcha2CodeTextBox" runat="server"></asp:TextBox> <asp:Label ID="Captcha2CorrectLabel" runat="server" CssClass="correct" Text="Correct!" Visible="false"></asp:Label> <asp:Label ID="Captcha2IncorrectLabel" runat="server" CssClass="incorrect" Text="Incorrect!" Visible="false"></asp:Label> </div> </fieldset> <asp:Button ID="SubmitFormButton" runat="server" Text="Submit Form" /> </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; using BotDetect; public partial class _Default : System.Web.UI.Page { protected void Page_PreRender(object sender, EventArgs e) { // Captcha2 code-behind setup Captcha2.CodeLength = 4; Captcha2.CodeStyle = CodeStyle.Alpha; Captcha2.DisallowedCodeSubstringsList = new List<string> { "AAA", "BBB", "CCC" }; Captcha2.CodeTimeout = 900; // 15 minutes // only re-calcualated on form load ImageStyle[] imageStyles = { ImageStyle.BlackOverlap, ImageStyle.Graffiti, ImageStyle.Overlap }; Captcha2.ImageStyle = CaptchaRandomization.GetRandomImageStyle(imageStyles); Captcha2.ImageSize = new System.Drawing.Size(120, 35); Captcha2.ImageFormat = ImageFormat.Png; Captcha2.CustomDarkColor = System.Drawing.Color.DarkGreen; Captcha2.CustomLightColor = System.Drawing.ColorTranslator.FromHtml("#eeeeff"); Captcha2.SoundEnabled = true; Captcha2.SoundStyle = SoundStyle.Dispatch; Captcha2.SoundFormat = SoundFormat.WavPcm8bit8kHzMono; Captcha2.SoundRegenerationMode = SoundRegenerationMode.None; Captcha2.Locale = "fr-CA"; Captcha2.ImageTooltip = "Custom Canadian French Captcha image tooltip"; Captcha2.SoundTooltip = "Custom Canadian French Captcha sound icon tooltip"; Captcha2.ReloadTooltip = "Custom Canadian French Captcha reload icon tooltip"; Captcha2.HelpLinkUrl = "custom-canadian-french-captcha-help-page.html"; Captcha2.HelpLinkText = "Custom Canadian French Captcha help link text"; Captcha2.ReloadEnabled = true; Captcha2.UseSmallIcons = true; Captcha2.UseHorizontalIcons = true; Captcha2.SoundIconUrl = ""; Captcha2.ReloadIconUrl = ""; Captcha2.IconsDivWidth = 50; Captcha2.HelpLinkEnabled = true; Captcha2.HelpLinkMode = HelpLinkMode.Image; Captcha2.TabIndex = 15; Captcha2.AdditionalCssClasses = ""; Captcha2.AdditionalInlineCss = ""; Captcha2.AddScriptInclude = true; Captcha2.AddInitScript = true; Captcha2.AutoUppercaseInput = true; Captcha2.AutoFocusInput = true; Captcha2.AutoClearInput = true; Captcha2.AutoReloadExpiredCaptchas = true; Captcha2.AutoReloadTimeout = 3600; // 1 hour Captcha2.SoundStartDelay = 1000; // 1 second Captcha2.RemoteScriptEnabled = true; // Form validation if (IsPostBack) { bool isHuman1 = Captcha1.Validate(); if (isHuman1) { Captcha1CorrectLabel.Visible = true; Captcha1IncorrectLabel.Visible = false; } else { Captcha1CorrectLabel.Visible = false; Captcha1IncorrectLabel.Visible = true; } bool isHuman2 = Captcha2.Validate(); if (isHuman2) { Captcha2CorrectLabel.Visible = true; Captcha2IncorrectLabel.Visible = false; } else { Captcha2CorrectLabel.Visible = false; Captcha2IncorrectLabel.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="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.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="BotDetectCaptcha.ashx" type="BotDetect.Web.CaptchaHandler, BotDetect"/> </handlers> </system.webServer> <botDetect helpLinkEnabled="true" helpLinkMode="image" /> </configuration>
Current BotDetect Versions
-
BotDetect ASP.NET CAPTCHA
2019-07-22v4.4.2 -
BotDetect Java CAPTCHA
2019-07-22v4.0.Beta3.7 -
BotDetect PHP CAPTCHA
2019-07-22v4.2.5