ASP.NET MVC 4.0 Application Template CAPTCHA C# ASPX Code Example

The ASP.NET MVC 4.0 application template Captcha C# ASPX example project shows how to use the BotDetect CAPTCHA MvcSimpleCaptcha control in ASP.NET MVC 4.0 C# web applications using ASPX views.

First Time Here?

Check the BotDetect ASP.NET MVC Captcha Simple API Quickstart for key integration steps.

Starting with the default ASP.NET MVC 4.0 Internet Application Visual Studio 2012 project template (File > New Project > Installed > Templates > Visual C# > Web > ASP.NET MVC 4 Web Application > Template: Internet Application, View Engine: ASPX), the example includes all code required to add CAPTCHA validation to the Account controller Register action (Views\Account\Register.aspx and Controllers\AccountController.cs).

The example also shows how to complement server-side CAPTCHA validation with client-side Ajax CAPTCHA validation using ASP.NET MVC 4.0 unobtrusive validation (based on jQuery) applied to all form fields (Scripts\captcha.validate.js).

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 application template Captcha Simple API example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET\WebApp\SimpleAPI\Mvc40CaptchaExample\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\Account\Register.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<AspNetMvc40CaptchaExampleAspxCSharp.Models.RegisterModel>" %>

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

<asp:Content ID="registerTitle" ContentPlaceHolderID="TitleContent" 
runat="server">
  Register
</asp:Content>



<asp:Content ID="registerContent" ContentPlaceHolderID="MainContent" 
runat="server">
  <hgroup class="title">
    <h1>Register.</h1>
    <h2>Create a new account.</h2>
  </hgroup>

  <% using (Html.BeginForm("Register", "Account"))
     { %>
  <%: Html.AntiForgeryToken() %>
  <%: Html.ValidationSummary() %>

  <fieldset class="register">
    <legend>Registration Form</legend>
    <ol>
      <li>
        <%: Html.LabelFor(m => m.UserName) %>
        <%: Html.TextBoxFor(m => m.UserName) %>
      </li>
      <li>
        <%: Html.LabelFor(m => m.Password) %>
        <%: Html.PasswordFor(m => m.Password) %>
      </li>
      <li>
        <%: Html.LabelFor(m => m.ConfirmPassword) %>
        <%: Html.PasswordFor(m => m.ConfirmPassword) %>
      </li>
      <% // showing Captcha on the form:
         // add SimpleCaptcha validation controls to the protected action  
         MvcSimpleCaptcha registrationCaptcha = new MvcSimpleCaptcha("RegistrationCaptcha");
         %>

      <li>
        <%: Html.Label("CaptchaCode", "Retype the code from the picture") %>
        <%: Html.SimpleCaptcha(registrationCaptcha) %>
        <%: Html.TextBox("CaptchaCode", "", new { @class = "captchaVal" }) %>
      </li>
      
    </ol>
    <input type="submit" value="Register" />
  </fieldset>
  <% } %>
</asp:Content>

<asp:Content ID="scriptsContent" ContentPlaceHolderID="ScriptsSection" 
runat="server">
  <%: Scripts.Render("~/bundles/jqueryval") %>
  <%-- client-side SimpleCaptcha validation script inlcude --%>
  <%: Scripts.Render("~/Scripts/captcha.validate.js") %>
</asp:Content>

To display Captcha protection on the Register View, we first ensure we can use BotDetect members and the application code by Import-ing the relevant namespaces.

When we have the registrationCaptcha object, displaying the Captcha is as easy as calling the Html.SimpleCaptcha() helper with it as a parameter.

We also add a Html.Label() and a Html.TextBox() to complete the SimpleCaptcha elements on the form; note that the textbox has it's CSS class set to captchaVal – we'll use this class to dynamically add unobtrusive jQuery validation of the user's Captcha input.

The client-side SimpleCaptcha validation rules are defined in a JavaScript file called captcha.validate.js, which we include in the ScriptsSection content placeholder after all other jQuery validation scripts in the jqueryval bundle.

Controllers\AccountController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using AspNetMvc40CaptchaExampleAspxCSharp.Models;

using BotDetect.Web.Mvc;

namespace AspNetMvc40CaptchaExampleAspxCSharp.Controllers
{
  [Authorize]
  public class AccountController : Controller
  {
  
    []

    //
    // POST: /Account/Register

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    [SimpleCaptchaValidation("CaptchaCode", "RegistrationCaptcha", 
    "Your input doesn't match displayed characters")]
    public ActionResult Register(RegisterModel model)
    {
      if (ModelState.IsValid)
      {
        // Attempt to register the user
        try
        {
          //WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
          //WebSecurity.Login(model.UserName, model.Password);

          return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
          ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
      }

      // If we got this far, something failed, redisplay form
      return View(model);
    }
    
    []
  }
}

Above we're showing only the part of AccountController code tied to SimpleCaptcha validation functionality, since that's what we're interested in.

After we've included the BotDetect.Web.Mvc namespace, we just need to add the SimpleCaptchaValidation attribute to the method processing Register 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 Register form),
  2. the ID of the SimpleCaptcha instance we're validating (which we set to RegistrationCaptcha in the file botdetect.xml
  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 Register form is submitted, and will automatically add a Model error with the error message configured above when SimpleCaptcha validation fails. So we don't need to check the Captcha validation status separately from the validation status of Model fields – checking if (ModelState.IsValid) is enough.

Scripts\captcha.validate.js

(function () {
  $.validator.setDefaults({
    // only validate fields when the form is submitted:
    // the SimpleCaptcha input must only be validated when the whole code string is
    // typed in, not after each individual character (onkeyup must be false);
    // onfocusout validation could be left on in more complex forms, but 
    // doesn't fit this example
    onkeyup: false,
    onfocusout: false,
    // always reload the Captcha image if remote validation failed,
    // since it will not be usable any more (a failed validation attempt
    // removes the attempted code for necessary SimpleCaptcha security
    showErrors: function (errorMap, errorList) {
      for (var i = 0; i < errorList.length; i++) {
        var element = errorList[i].element;
        var message = errorList[i].message;
        // check element css class and does the error message match remote
        // validation failure
        if (element.className.match(/captchaVal/) &&
            message === this.settings.messages[element.id].remote) {
          BotDetect.getInstanceByStyleName("RegisterCaptcha").reloadImage();
          $("form").valid();
        }
      }
    }
  });
})();


$(document).ready(function () {
  // add validation rules by CSS class, so we don't have to know the
  // exact client id of the Captcha code textbox
  $(".captchaVal").rules('add', {
    required: true,
    remote: BotDetect.getInstanceByStyleName("RegisterCaptcha").validationUrl,
    messages: {
      required: "Your input doesn't match displayed characters",
      remote: "Incorrect code, please try again"
    }
  });
});

Since ASP.NET MVC unobtrusive validation is based on the jquery.validate.js jQuery plugin, we add Captcha code textbox client-side validation by extending the validator settings as defined in its API.

We use the CSS class we gave the Captcha code textbox (captchaVal) to add validation rules making the Captcha code both a required field, and one validated remotely. Since secure Captcha validation can only be performed on the server, we make a validation Ajax request to the validation Url exposed by the client-side SimpleCaptcha object.

Furthermore, since each random Captcha code can only be attempted once for security reasons, we have to reload the Captcha image whenever Ajax Captcha validation fails (or it would be showing the user a code that cannot be validated anymore, making them always fail the validation even when they retype the Captcha code correctly). We do this in the validator showErrors() function, after we checked there is a remote SimpleCaptcha validation error.

For the same reason, the remote Captcha validation only needs to happen when the user has finished retyping the whole Captcha code, and must not trigger after each individual character has been typed. We achieve this by setting the validator onkeyup setting to false.

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 AspNetMvc40CaptchaExampleAspxCSharp
{
  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 = "Account", action = "Register", 
          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>
    <compilation debug="false" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    
    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <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.Helpers" 
        publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" 
        publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" 
        publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.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.

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>RegistrationCaptcha</name>
      <userInputID>CaptchaCode</userInputID>
      <codeLength>3-5</codeLength>
    </captchaStyle>
  </captchaStyles>

</botdetect>

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