ASP.NET MVC 4.0 Basic CAPTCHA C# ASPX Code Example

The ASP.NET MVC 4.0 Basic SimpleCaptcha C# ASPX 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 Simple API Quickstart for key integration steps.

ASP.NET MVC View code displaying CAPTCHA protection can be found in Views/Example/Index.aspx, and the ASP.NET MVC Controller code checking user input is in Controllers/ExampleController.cs.

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

→ ASP.NET MVC version:

→ .NET programming language:

→ View engine:

Installed Location

By default, the .NET 4.5 C# ASPX version of the ASP.NET MVC 4.0 Basic Captcha Simple API example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET\WebApp\SimpleAPI\Mvc40BasicCaptchaExample\ASPX\CSharp

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

Views\Example\Index.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<%-- namespaces needed to access BotDetect members --%>
<%@ Import Namespace="BotDetect.Web.Mvc" %>

<!DOCTYPE html>

<html>
<head runat="server">
  <meta name="viewport" content="width=device-width" />
  <title>BotDetect CAPTCHA Basic ASP.NET MVC 4.0 Example</title>
  <link href="<%: Url.Content("~/Style/Sheet.css") %>" rel="stylesheet" 
  type="text/css" />
  
</head>
<body>
  <h1>BotDetect CAPTCHA Basic ASP.NET MVC 4.0 Example</h1>

  <% using (Html.BeginForm())
     { %>
  <fieldset>
    <legend>CAPTCHA Protection Shown on an ASP.NET MVC View</legend>
    <div>
      <%: Html.Label("CaptchaCode", "Retype the code from the picture:") %>
      <% MvcSimpleCaptcha exampleCaptcha = new MvcSimpleCaptcha("ExampleCaptcha"); %>
      <%: Html.SimpleCaptcha(exampleCaptcha) %>
    </div>
    <div class="actions">
      <%: Html.TextBox("CaptchaCode") %>
      <input type="submit" value="Validate" />
      <%: Html.ValidationMessage("CaptchaCode") %>
    </div>
  </fieldset>
  <% } %>
</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 MvcSimpleCaptcha instance, and add it to the form by calling the Html.SimpleCaptcha() Html helper with it.

In this simplest case, we also use the Html.ValidationMessage helper to display Captcha validation errors.

botdetect.xml

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/net" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://captcha.com/schema/net 
      https://captcha.com/schema/net/botdetect-4.4.0.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>ExampleCaptcha</name>
      <userInputID>CaptchaCode</userInputID>
      <codeLength>3-5</codeLength>
    </captchaStyle>
  </captchaStyles>

</botdetect>

In botdetect.xml, we configure captcha options for the ExampleCaptcha captcha style name. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page .

Controllers\ExampleController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using AspNetMvc40BasicCaptchaExampleAspxCSharp.Models;

using BotDetect.Web.Mvc;

namespace AspNetMvc40BasicCaptchaExampleAspxCSharp.Controllers
{
  public class ExampleController : Controller
  {
    //
    // GET: /Example/

    public ActionResult Index()
    {
      return View();
    }


    //
    // POST: /Example/

    [HttpPost]
    [SimpleCaptchaValidation("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA code!")]
    public ActionResult Index(ExampleModel model)
    {

      return View(model);
    }

  }
}

After we've included the BotDetect.Web.Mvc namespace, we just need to add the SimpleCaptchaValidation attribute to the method processing form submissions. The attribute takes three parameters:

  1. the ID of the textbox containing the user's Captcha code input (which we named CaptchaCode on the form),
  2. the ID of the SimpleCaptcha instance we're validating (which we set to ExampleCaptcha in the MvcSimpleCaptcha constructor), and
  3. the error message to be shown when SimpleCaptcha validation fails.

When the SimpleCaptcha validation action filter attribute has been added, the SimpleCaptcha validation will trigger every time the form is submitted, and will automatically add a Model error with the error message configured above when SimpleCaptcha validation fails. The Html.ValidationMessage helper on the form will then display this error when SimpleCaptcha 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 AspNetMvc40BasicCaptchaExampleAspxCSharp
{
  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=169433
  -->
<configuration>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <httpRuntime targetFramework="4.5" />
    <compilation debug="false" targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
    <httpHandlers>
      <!-- register HttpHandler used for BotDetect Simple API requests -->
      <add verb="GET" path="BotDetectCaptcha.ashx" 
      type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
    </httpHandlers>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,
      HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" 
      scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.
      dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" 
      responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,
      HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" 
      scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.
      30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,
      bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,
      HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.
      TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      <!-- register HttpHandler used for BotDetect Simple API requests -->
      <remove name="BotDetectCaptchaHandler"/>
      <add name="BotDetectCaptchaHandler" preCondition="integratedMode" 
      verb="GET" path="BotDetectCaptcha.ashx" 
      type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" 
        publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
 </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.

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.