ASP.NET MVC 5 Application Template CAPTCHA C# Code Example

The ASP.NET MVC 5 application template Captcha C# Razor example project shows how to use the BotDetect CAPTCHA MvcCaptcha control in ASP.NET MVC 5.0 C# web applications.

First Time Here?

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

Starting with the default ASP.NET MVC 5 Web Application Visual Studio 2015 / 2013 project template (File > New Project > Installed > Templates > Visual C# > Web > ASP.NET Web Application > MVC), the example includes all code required to add CAPTCHA validation to the Account controller Register action (Views\Account\Register.cshtml 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 5 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:

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-aspnet.identity/csharp/ folder; and contains the following files:

Views\Account\Register.cshtml

@model AspNetMvc50CaptchaExampleCSharp.Models.RegisterViewModel

@* namespaces needed to access BotDetect members and the CaptchaHelper class *@
@using BotDetect.Web.Mvc;
@using AspNetMvc50CaptchaExampleCSharp.App_Code;

@{
  ViewBag.Title = "Register";
}

@* include BotDetect layout stylesheet in page <head> *@
@section HeadIncludes {
  <link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl" 
  rel="stylesheet" type="text/css" />
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("Register", "Account", FormMethod.Post, 
  new { @class = "form-horizontal", role = "form" }))
{
  @Html.AntiForgeryToken()
  <h4>Create a new account.</h4>
  <hr />

  <div class="col-md-6" id="form-container">

    @Html.ValidationSummary()

    <div class="form-group">
      @Html.LabelFor(m => m.UserName, new { @class = "col-md-4 control-label" })
      <div class="col-md-8">
        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
      </div>
    </div>

    <div class="form-group">
      @Html.LabelFor(m => m.Password, new { @class = "col-md-4 control-label" })
      <div class="col-md-8">
        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
      </div>
    </div>
    <div class="form-group">
      @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-4 control-label" })
      <div class="col-md-8">
        @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
      </div>
    </div>

    @* showing Captcha on the form:
      add Captcha validation controls to the protected action View,
      but only if the Captcha hasn't already been solved *@

    @{MvcCaptcha registrationCaptcha = CaptchaHelper.GetRegistrationCaptcha(); }
    @if (!registrationCaptcha.IsSolved)
    {
      <div class="form-group">
        <div class="col-md-offset-4 col-md-8">
          @Html.Captcha(registrationCaptcha)
        </div>

        @Html.Label("Retype the code", new { @class = "col-md-4 control-label", 
        @for = "CaptchaCode" })

        <div class="col-md-8">
          @Html.TextBox("CaptchaCode", null, new { @class = "form-control captchaVal" })
        </div>
      </div>
    }

    <div class="form-group" id="form-submit">
      <div class="col-md-offset-4 col-md-8">
        <input type="submit" class="btn btn-default" value="Register" />
      </div>
    </div>

  </div>
}
@section Scripts {
  @Scripts.Render("~/bundles/jqueryval")
  @Scripts.Render("~/Scripts/captcha.validate.js")
}

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

Then, we include the BotDetect layout stylesheet in the page <head> (through the associated HeadIncludes section), to make Captcha elements display correctly.

To reduce the amount of code added to the View and make it clearer, we create the registrationCaptcha object (an instance of the BotDetect MvcCaptcha class) using the CaptchaHelper.

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

We also add a Html.Label() and a Html.TextBox() to complete the Captcha 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.

Note that we add Captcha fields to the form only if the IsSolved flag of the Captcha object hasn't been set. This is a small usability improvement for users who don't have JavaScript enabled: if they solve the Captcha correctly but validation of other form fields fails, they won't have to solve the Captcha again (since they have already proven to be a real visitor instead of a bot). Of course, if this is not something you are concerned about, you can simply display the Captcha without this check.

The client-side Captcha 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.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using AspNetMvc50CaptchaExampleCSharp.Models;

using BotDetect.Web.Mvc;

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

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    [CaptchaValidationActionFilter("CaptchaCode", "RegistrationCaptcha", 
    "Incorrect CAPTCHA Code!")]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
      if (ModelState.IsValid)
      {
        var user = new ApplicationUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
          await SignInAsync(user, isPersistent: false);
          MvcCaptcha.ResetCaptcha("RegistrationCaptcha");
          return RedirectToAction("Index", "Home");
        }
        else
        {
          AddErrors(result);
        }
      }

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

    []
  }
}

Above we're showing only the part of AccountController code tied to Captcha 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 CaptchaValidationActionFilter 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 Captcha instance we're validating (which we set to RegistrationCaptcha in the CaptchaHelper class), and
  3. 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 Register form is submitted, and will automatically add a Model error with the error message configured above when Captcha 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.

The only other change we make is calling MvcCaptcha.ResetCaptcha() after the user account has been successfully created. As the code comment says, we do this to ensure the user is shown a new Captcha if they open the Register form again in the same session. This is tied to the IsSolved check we use on the form, so if you decide not to use that check, resetting the Captcha status is unnecessary.

App_Code\CaptchaHelper.cs

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

using BotDetect.Web.Mvc;

namespace AspNetMvc50CaptchaExampleCSharp.App_Code
{
  public static class CaptchaHelper
  {
    public static MvcCaptcha GetRegistrationCaptcha()
    {
      // create the control instance
      MvcCaptcha registrationCaptcha = new MvcCaptcha("RegistrationCaptcha");

      // set up client-side processing of the Captcha code input textbox
      registrationCaptcha.UserInputID = "CaptchaCode";

      // Captcha settings
      registrationCaptcha.ImageSize = new System.Drawing.Size(255, 50);

      return registrationCaptcha;
    }
  }
}

Since there are many properties of the Captcha object you might want to set, we separate MvcCaptcha instance creation in a class apart from View code. This way we keep the View code short, and can have multiple Captchas in different Views without having to keep Captcha code scattered over each View code.

Each Captcha instance should have a unique ID, which we pass to the MvcCaptcha constructor (and which is also passed to the CaptchaValidationActionFilter attribute in Controller code).

Setting the UserInputID property to the client-side ID of the Captcha code input textbox is necessary to wire-up client-side input and validation functionality.

Scripts\captcha.validate.js

(function () {
  $.validator.setDefaults({
    // only validate fields when the form is submitted:
    // the Captcha 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 Captcha 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) {
          element.Captcha.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: $(".captchaVal").get(0).Captcha.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 Captcha 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 Captcha 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.

Views\Shared\_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>@ViewBag.Title - My ASP.NET Application</title>
  @RenderSection("HeadIncludes", required: false)
  @Styles.Render("~/Content/css")
  @Scripts.Render("~/bundles/modernizr")
</head>
<body>
  <div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-
        target=".navbar-collapse">
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        @Html.ActionLink("Application name", "Index", "Home", null, new { @class 
        = "navbar-brand" })
      </div>
      <div class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
          <li>@Html.ActionLink("Home", "Index", "Home")</li>
          <li>@Html.ActionLink("About", "About", "Home")</li>
          <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
        </ul>
        @Html.Partial("_LoginPartial")
      </div>
    </div>
  </div>
  <div class="container body-content">
    @RenderBody()
    <hr />
    <footer>
      <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
    </footer>
  </div>

  @Scripts.Render("~/bundles/jquery")
  @Scripts.Render("~/bundles/bootstrap")
  @RenderSection("scripts", required: false)
</body>
</html>

There is only a single small change made in the main site template: we add a HeadIncludes content section, which allows us to include the BotDetect layout stylesheet in the page head when it's needed.

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 AspNetMvc50CaptchaExampleCSharp
{
  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=301880
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.
    EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, 
    PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
    <section name="botDetect" requirePermission="false" type="BotDetect.
    Configuration.BotDetectConfigurationSection, BotDetect"/>
    <!-- For more information on Entity Framework configuration, visit http://go.
    microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;
    AttachDbFilename=|DataDirectory|\aspnet-AspNetMvc50CaptchaExampleCSharp-
    20140225103220.mdf;Initial Catalog=aspnet-AspNetMvc50CaptchaExampleCSharp-
    20140225103220;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>
  <system.web>
  <authentication mode="None"/>
  <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"/>
  <modules>
    <remove name="FormsAuthenticationModule"/>
  </modules>
  <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-2.0.0.0" newVersion="2.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>
    <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="WebGrease" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-1.0.0.0" newVersion="1.0.0.0"/>
    </dependentAssembly>
  </assemblyBinding>
  </runtime>
  <entityFramework>
  <defaultConnectionFactory 
    type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
    <parameter value="v11.0"/>
    </parameters>
  </defaultConnectionFactory>
  <providers>
    <provider invariantName="System.Data.SqlClient" 
    type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
  </providers>
  </entityFramework>
  <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.