ASP.NET MVC 5.0 Basic CAPTCHA C# Code Example
The ASP.NET MVC 5.0 Basic Captcha C# example project shows the most basic source code required to protect an ASP.NET MVC form with BotDetect CAPTCHA and validate the user input.
First Time Here?
Check the BotDetect ASP.NET MVC Captcha Quickstart for key integration steps.
ASP.NET MVC View code displaying CAPTCHA protection can be found in Views/Example/Index.cshtml
, and the ASP.NET MVC Controller code checking user input is in Controllers/ExampleController.cs
.
→ ASP.NET MVC version:
- ASP.NET MVC Core 1/2
- ASP.NET MVC 5.0
- ASP.NET MVC 4.0
→ .NET programming language:
- C#
- VB.NET
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-mvc5-api_basics/csharp/
folder; and contains the following files:
Views\Example\Index.cshtml
@* namespaces needed to access BotDetect members *@ @using BotDetect.Web.Mvc; @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>BotDetect ASP.NET CAPTCHA Validation: Basic ASP.NET MVC CAPTCHA Code Example</title> <link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Style/Sheet.css")" rel="stylesheet" type="text/css" /> </head> <body> <div class="column"> <h1>BotDetect ASP.NET CAPTCHA Validation: <br /> Basic ASP.NET MVC CAPTCHA Code Example</h1> @using (Html.BeginForm()) { <fieldset> <legend>ASP.NET MVC CAPTCHA Validation</legend> <div> @Html.Label("CaptchaCode", "Retype the code from the picture: ") @{ MvcCaptcha exampleCaptcha = new MvcCaptcha("ExampleCaptcha"); exampleCaptcha.UserInputID = "CaptchaCode";} @Html.Captcha(exampleCaptcha) </div> <div class="actions"> @Html.TextBox("CaptchaCode") <input type="submit" value="Validate" /> @Html.ValidationMessage("CaptchaCode") @if ((Request.HttpMethod == "POST") && ViewData.ModelState.IsValid) { <span class="correct">Correct!</span> } </div> </fieldset> } </div> </body> </html>
To display Captcha protection on the example View, we first ensure we can use BotDetect members by Import
-ing the relevant namespaces.
We then create a MvcCaptcha
instance, and add it to the form by calling the Html.Captcha()
Html helper with it.
In this simplest case, we also use the Html.ValidationMessage
helper to display Captcha validation errors.
Controllers\ExampleController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BotDetect.Web.Mvc; using AspNetMvc50BasicCaptchaExampleCSharp.Models; namespace AspNetMvc50BasicCaptchaExampleCSharp.Controllers { public class ExampleController : Controller { // // GET: /Example/ public ActionResult Index() { return View(); } // // POST: /Example/ [HttpPost] [CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Incorrect!")] public ActionResult Index(ExampleModel model) { MvcCaptcha.ResetCaptcha("ExampleCaptcha"); return View(model); } } }
After we've included the BotDetect.Web.Mvc
namespace, we just need to add the CaptchaValidationActionFilter
attribute to the method processing form submissions. The attribute takes three parameters:
- the ID of the textbox containing the user's Captcha code input (which we named
CaptchaCode
on the form), - the ID of the Captcha instance we're validating (which we set to
ExampleCaptcha
in theMvcCaptcha
constructor), and - the error message to be shown when Captcha validation fails.
When the Captcha validation action filter attribute has been added, the Captcha validation will trigger every time the form is submitted, and will automatically add a Model error with the error message configured above when Captcha validation fails. The Html.ValidationMessage
helper on the form will then display this error when Captcha validation fails.
App_Start\RouteConfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace AspNetMvc50BasicCaptchaExampleCSharp { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // BotDetect requests must not be routed routes.IgnoreRoute("{*botdetect}", new { botdetect = @"(.*)BotDetectCaptcha\.ashx" }); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Example", action = "Index", id = UrlParameter.Optional } ); } } }
We configure ASP.NET Routing to ignore BotDetect requests, since they do not conform to any MVC-related patterns. The regex defining requests to ignore must match the path configured for the BotDetect HttpHandler
registered in web.config
.
Web.config
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=301880 --> <configuration> <configSections> <section name="botDetect" requirePermission="false" type="BotDetect.Configuration.BotDetectConfigurationSection, BotDetect"/> </configSections> <appSettings> <add key="webpages:Version" value="3.0.0.0"/> <add key="webpages:Enabled" value="false"/> <add key="ClientValidationEnabled" value="false"/> <add key="UnobtrusiveJavaScriptEnabled" value="false"/> </appSettings> <system.web> <compilation debug="false" targetFramework="4.5.1"/> <httpRuntime targetFramework="4.5.1"/> <!-- configure Session State for BotDetect use --> <sessionState mode="InProc" cookieless="AutoDetect" timeout="20" sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/> <httpHandlers> <!-- register HttpHandler used for BotDetect Captcha requests --> <add verb="GET" path="BotDetectCaptcha.ashx" type="BotDetect.Web.CaptchaHandler, BotDetect"/> </httpHandlers> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <handlers> <!-- register HttpHandler used for BotDetect Captcha requests --> <remove name="BotDetectCaptchaHandler"/> <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" path="BotDetectCaptcha.ashx" type="BotDetect.Web.CaptchaHandler, BotDetect"/> </handlers> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> <botDetect helpLinkEnabled="true" helpLinkMode="image" /> </configuration>
To allow the application to use BotDetect Captcha protection, we must register the BotDetect HttpHandler
in both <system.web><httpHandlers>
and <system.webServer><handlers>
configuration sections, and enable and configure ASP.NET sessionState
.
The <dependentAssembly>
entry for System.Web.Mvc
is also needed to make all ASP.NET MVC dependencies referenced by the BotDetect MVC assembly point to the correct ASP.NET MVC version.
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