MVC Captcha: A step-by-step Integration Guide

Unlike Recaptcha the Stalker -- BotDetect CAPTCHA works in China! Licensable source-code; self-hosted -- doesn't stalk -- nor does it slurp your form-data! Think: GDPR & LGPD!

Click on the link below that matches your integration usage scenario:

..............................................................

MVC Core 2 Captcha

Step-1) Installation

Reference the BotDetect ASP.NET CAPTCHA library as described on the main product page:

Step-2) Displaying Captcha in a Form

Step-2.1) Register the BotDetectCaptcha.ashx Path

Add the highlighted lines into your app's Startup class (Startup.cs):

public class Startup
{
  public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                        ILoggerFactory loggerFactory)
  {
    ...

    // configure Session middleware
    app.UseSession();

    // configure your application pipeline to use Captcha middleware
    // Important! UseCaptcha(...) must be called after the UseSession() call
    app.UseCaptcha(Configuration);

    ...
  }


  public void ConfigureServices(IServiceCollection services)
  {
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddMemoryCache(); // Adds a default in-memory 
                                        // implementation of 
                                        // IDistributedCache

    // Add framework services.
    services.AddMvc();

    // Add Session services.
    services.AddSession(options =>
    {
      options.IdleTimeout = TimeSpan.FromMinutes(20);
      options.Cookie.IsEssential = true;
    });
  }
}

Step-2.2) Place Captcha in Your Form

Make the CaptchaTagHelper class available to all Razor views in your app, by adding the addTagHelper directive to the Views/_ViewImports.cshtml file:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "BotDetect.Web.Mvc.CaptchaTagHelper, BotDetect.Web.Mvc"

To the YourViewWithCaptcha.chtml file -- at the exact place where you want to be displaying captcha challenges -- add the <captcha> tag.

In order for captcha layout be displayed properly, add the captcha stylesheet to page header.

[…]
@section header {
  <environment names="Development,Staging,Production">
      <link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"
            rel="stylesheet" type="text/css" />
[…]
}

[…]

<label asp-for="CaptchaCode">Retype the code from the picture:</label>
<captcha id="ExampleCaptcha" user-input-id="CaptchaCode" />
<div class="actions">
<input asp-for="CaptchaCode" />
<input type="submit" value="Validate" />
<span asp-validation-for="CaptchaCode"></span>
@if ((Context.Request.Method == "POST") && ViewData.ModelState.IsValid)
{
  <span class="correct">Correct!</span>
}
</div>

[…]

Add the CaptchaCode property to Form's Model:

public string CaptchaCode { get; set; }

Step-3) Captcha Validation

Mark the protected Controller action with the CaptchaValidationActionFilter attribute to include Captcha validation in ModelState.IsValid checks:

using BotDetect.Web.Mvc;

[…]

[HttpPost]
[CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Wrong Captcha!")]
public ActionResult ExampleAction(ExampleModel model)
{
  if (!ModelState.IsValid)
  {  
    // TODO: Captcha validation failed, show error message      
  }  
  else
  {  
    // TODO: captcha validation succeeded; execute the protected action  

    // Reset the captcha if your app's workflow continues with the same view
    MvcCaptcha.ResetCaptcha("ExampleCaptcha");     
  }  

Step-4) Configuring the Other ASP.NET Captcha Options

All BotDetect ASP.NET CAPTCHA Traditional API configuration options are described in the Traditional API configuration options page.

..............................................................

MVC Core 1 Captcha

Step-1) Installation

Reference the BotDetect ASP.NET CAPTCHA library as described on the main product page:

Step-2) Displaying Captcha in a Form

Step-2.1) Register the BotDetectCaptcha.ashx Path

Add the highlighted lines into your app's Startup class (Startup.cs):

public class Startup
{
  public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                        ILoggerFactory loggerFactory)
  {
    ...

    // configure Session middleware
    app.UseSession();

    // configure your application pipeline to use Captcha middleware
    // Important! UseCaptcha(...) must be called after the UseSession() call
    app.UseCaptcha(Configuration);

    ...
  }


  public void ConfigureServices(IServiceCollection services)
  {
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddMemoryCache(); // Adds a default in-memory 
                                        // implementation of 
                                        // IDistributedCache

    // Add framework services.
    services.AddMvc();

    // Add Session services.
    services.AddSession(options =>
    {
      options.IdleTimeout = TimeSpan.FromMinutes(20);
    });
  }
}

Step-2.2) Place Captcha in Your Form

Make the CaptchaTagHelper class available to all Razor views in your app, by adding the addTagHelper directive to the Views/_ViewImports.cshtml file:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "BotDetect.Web.Mvc.CaptchaTagHelper, BotDetect.Web.Mvc"

To the YourViewWithCaptcha.chtml file -- at the exact place where you want to be displaying captcha challenges -- add the <captcha> tag.

In order for captcha layout be displayed properly, add the captcha stylesheet to page header.

[…]
@section header {
  <environment names="Development,Staging,Production">
      <link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"
            rel="stylesheet" type="text/css" />
[…]
}

[…]

<label asp-for="CaptchaCode">Retype the code from the picture:</label>
<captcha id="ExampleCaptcha" user-input-id="CaptchaCode" />
<div class="actions">
<input asp-for="CaptchaCode" />
<input type="submit" value="Validate" />
<span asp-validation-for="CaptchaCode"></span>
@if ((Context.Request.Method == "POST") && ViewData.ModelState.IsValid)
{
  <span class="correct">Correct!</span>
}
</div>

[…]

Add the CaptchaCode property to Form's Model:

public string CaptchaCode { get; set; }

Step-3) Captcha Validation

Mark the protected Controller action with the CaptchaValidationActionFilter attribute to include Captcha validation in ModelState.IsValid checks:

using BotDetect.Web.Mvc;

[…]

[HttpPost]
[CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Wrong Captcha!")]
public ActionResult ExampleAction(ExampleModel model)
{
  if (!ModelState.IsValid)
  {  
    // TODO: Captcha validation failed, show error message      
  }  
  else
  {  
    // TODO: captcha validation succeeded; execute the protected action  

    // Reset the captcha if your app's workflow continues with the same view
    MvcCaptcha.ResetCaptcha("ExampleCaptcha");     
  }  

Step-4) Configuring the Other ASP.NET Captcha Options

All BotDetect ASP.NET CAPTCHA Traditional API configuration options are described in the Traditional API configuration options page.

..............................................................

MVC 5 Captcha

Step-1) Installation

Reference the BotDetect ASP.NET CAPTCHA library as described on the main product page:

Step-2) Displaying Captcha in a Form

Step-2.1) Register the BotDetectCaptcha.ashx Path

Exclude BotDetect paths from ASP.NET MVC Routing:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  // BotDetect requests must not be routed
  routes.IgnoreRoute("{*botdetect}",
    new { botdetect = @"(.*)BotDetectCaptcha\.ashx" });

  […]

Update your application configuration (the web.config file):

<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"/>
</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>

Step-2.2) Place Captcha in Your Form

In the Forms's View code: import the BotDetect namespace, include BotDetect styles in page <head>, create a MvcCaptcha object and pass it to the Captcha HtmlHelper:

@using BotDetect.Web.Mvc;

[…]

  <link
    href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"
    rel="stylesheet" type="text/css" />
</head>

[…]

@{ 
MvcCaptcha exampleCaptcha = new MvcCaptcha("ExampleCaptcha");
exampleCaptcha.UserInputID = "CaptchaCode"; 
}
@Html.Captcha(exampleCaptcha)
@Html.TextBox("CaptchaCode")

Add the CaptchaCode property to Form's Model:

public string CaptchaCode { get; set; }

Step-3) Captcha Validation

Mark the protected Controller action with the CaptchaValidationActionFilter attribute to include Captcha validation in ModelState.IsValid checks:

using BotDetect.Web.Mvc;

[…]

[HttpPost]
[CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Wrong Captcha!")]
public ActionResult ExampleAction(ExampleModel model)
{
  if (!ModelState.IsValid)
  {
    // TODO: Captcha validation failed, show error message
  }
  else
  {
    // TODO: captcha validation succeeded; execute the protected action

    // Reset the captcha if your app's workflow continues with the same view
    MvcCaptcha.ResetCaptcha("ExampleCaptcha");
  }

Step-4) Configuring the Other ASP.NET Captcha Options

All BotDetect ASP.NET CAPTCHA Traditional API configuration options are described in the Traditional API configuration options page.

..............................................................

MVC 4 Captcha

Step-1) Installation

Reference the BotDetect ASP.NET CAPTCHA library as described on the main product page:

Step-2) Displaying Captcha in a Form

Step-2.1) Register the BotDetectCaptcha.ashx Path

Exclude BotDetect paths from ASP.NET MVC Routing:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  // BotDetect requests must not be routed
  routes.IgnoreRoute("{*botdetect}",
    new { botdetect = @"(.*)BotDetectCaptcha\.ashx" });

  […]

Update your application configuration (the web.config file):

<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"/>
</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>

Step-2.2) Place Captcha in Your Form

In the Forms's View code: import the BotDetect namespace, include BotDetect styles in page <head>, create a MvcCaptcha object and pass it to the Captcha HtmlHelper:

In the Forms's View code: import the BotDetect namespace, include BotDetect styles in page <head>, create a MvcCaptcha object and pass it to the Captcha HtmlHelper:

<%@ Import Namespace="BotDetect.Web.Mvc" %>

[…]

  <link
    href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>"
    rel="stylesheet" type="text/css" />
</head>

[…]

<%
    MvcCaptcha exampleCaptcha = new MvcCaptcha("ExampleCaptcha");
    exampleCaptcha.UserInputID = "CaptchaCode";
%>
<%: Html.Captcha(exampleCaptcha) %>
<%: Html.TextBox("CaptchaCode") %>

Add the CaptchaCode property to Form's Model:

public string CaptchaCode { get; set; }

Step-3) Captcha Validation

Mark the protected Controller action with the CaptchaValidationActionFilter attribute to include Captcha validation in ModelState.IsValid checks:

using BotDetect.Web.Mvc;

[…]

[HttpPost]
[CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Wrong Captcha!")]
public ActionResult ExampleAction(ExampleModel model)
{
  if (!ModelState.IsValid)
  {
    // TODO: Captcha validation failed, show error message
  }
  else
  {
    // TODO: captcha validation succeeded; execute the protected action

    // Reset the captcha if your app's workflow continues with the same view
    MvcCaptcha.ResetCaptcha("ExampleCaptcha");
  }

Step-4) Configuring the Other ASP.NET Captcha Options

All BotDetect ASP.NET CAPTCHA Traditional API configuration options are described in the Traditional API configuration options page.

..............................................................

MVC 3 Captcha

Step-1) Installation

Reference the BotDetect ASP.NET CAPTCHA library as described on the main product page:

Step-2) Displaying Captcha in a Form

Step-2.1) Register the BotDetectCaptcha.ashx Path

Exclude BotDetect paths from ASP.NET MVC Routing:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  // BotDetect requests must not be routed
  routes.IgnoreRoute("{*botdetect}",
    new { botdetect = @"(.*)BotDetectCaptcha\.ashx" });

  […]

Update your application configuration (the web.config file):

<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"/>
</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>

Step-2.2) Place Captcha in Your Form

In the Forms's View code: import the BotDetect namespace, include BotDetect styles in page <head>, create a MvcCaptcha object and pass it to the Captcha HtmlHelper:

In the Forms's View code: import the BotDetect namespace, include BotDetect styles in page <head>, create a MvcCaptcha object and pass it to the Captcha HtmlHelper:

<%@ Import Namespace="BotDetect.Web.Mvc" %>

[…]

  <link
    href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>"
    rel="stylesheet" type="text/css" />
</head>

[…]

<%
    MvcCaptcha exampleCaptcha = new MvcCaptcha("ExampleCaptcha");
    exampleCaptcha.UserInputID = "CaptchaCode";
%>
<%: Html.Captcha(exampleCaptcha) %>
<%: Html.TextBox("CaptchaCode") %>

Add the CaptchaCode property to Form's Model:

public string CaptchaCode { get; set; }

Step-3) Captcha Validation

Mark the protected Controller action with the CaptchaValidationActionFilter attribute to include Captcha validation in ModelState.IsValid checks:

using BotDetect.Web.Mvc;

[…]

[HttpPost]
[CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Wrong Captcha!")]
public ActionResult ExampleAction(ExampleModel model)
{
  if (!ModelState.IsValid)
  {
    // TODO: Captcha validation failed, show error message
  }
  else
  {
    // TODO: captcha validation succeeded; execute the protected action

    // Reset the captcha if your app's workflow continues with the same view
    MvcCaptcha.ResetCaptcha("ExampleCaptcha");
  }

Step-4) Configuring the Other ASP.NET Captcha Options

All BotDetect ASP.NET CAPTCHA Traditional API configuration options are described in the Traditional API configuration options page.

..............................................................

MVC 2 Captcha

Step-1) Installation

Reference the BotDetect ASP.NET CAPTCHA library as described on the main product page:

Step-2) Displaying Captcha in a Form

Step-2.1) Register the BotDetectCaptcha.ashx Path

Exclude BotDetect paths from ASP.NET MVC Routing:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  // BotDetect requests must not be routed
  routes.IgnoreRoute("{*botdetect}",
    new { botdetect = @"(.*)BotDetectCaptcha\.ashx" });

  […]

Update your application configuration (the web.config file):

<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"/>
</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>

Step-2.2) Place Captcha in Your Form

In the Forms's View code: import the BotDetect namespace, include BotDetect styles in page <head>, create a MvcCaptcha object and pass it to the Captcha HtmlHelper:

<%@ Import Namespace="BotDetect.Web.Mvc" %>

[…]

  <link
    href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>"
    rel="stylesheet" type="text/css" />
</head>

[…]

<%
    MvcCaptcha exampleCaptcha = new MvcCaptcha("ExampleCaptcha");
    exampleCaptcha.UserInputID = "CaptchaCode";
%>
<%: Html.Captcha(exampleCaptcha) %>
<%: Html.TextBox("CaptchaCode") %>

Add the CaptchaCode property to Form's Model:

public string CaptchaCode { get; set; }

Step-3) Captcha Validation

Mark the protected Controller action with the CaptchaValidationActionFilter attribute to include Captcha validation in ModelState.IsValid checks:

using BotDetect.Web.Mvc;

[…]

[HttpPost]
[CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Wrong Captcha!")]
public ActionResult ExampleAction(ExampleModel model)
{
  if (!ModelState.IsValid)
  {
    // TODO: Captcha validation failed, show error message
  }
  else
  {
    // TODO: captcha validation succeeded; execute the protected action

    // Reset the captcha if your app's workflow continues with the same view
    MvcCaptcha.ResetCaptcha("ExampleCaptcha");
  }

Step-4) Configuring the Other ASP.NET Captcha Options

All BotDetect ASP.NET CAPTCHA Traditional API configuration options are described in the Traditional API configuration options page.

..............................................................

MVC 1 Captcha

Step-1) Installation

Reference the BotDetect ASP.NET CAPTCHA library as described on the main product page:

Step-2) Displaying Captcha in a Form

Step-2.1) Register the BotDetectCaptcha.ashx Path

Exclude BotDetect paths from ASP.NET MVC Routing:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  // BotDetect requests must not be routed
  routes.IgnoreRoute("{*botdetect}",
    new { botdetect = @"(.*)BotDetectCaptcha\.ashx" });

  […]

Update your application configuration (the web.config file):

<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"/>
</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>

Step-2.2) Place Captcha in Your Form

In the Forms's View code: import the BotDetect namespace, include BotDetect styles in page <head>, create a MvcCaptcha object and pass it to the Captcha HtmlHelper:

<%@ Import Namespace="BotDetect.Web.Mvc" %>

[…]

  <link
    href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>"
    rel="stylesheet" type="text/css" />
</head>

[…]

<%
    MvcCaptcha exampleCaptcha = new MvcCaptcha("ExampleCaptcha");
    exampleCaptcha.UserInputID = "CaptchaCode";
%>
<%= Html.Captcha(exampleCaptcha) %>
<%= Html.TextBox("CaptchaCode") %>

Add the CaptchaCode property to Form's Model:

public string CaptchaCode { get; set; }

Step-3) Captcha Validation

Mark the protected Controller action with the CaptchaValidationActionFilter attribute to include Captcha validation in ModelState.IsValid checks:

using BotDetect.Web.Mvc;

[…]

[HttpPost]
[CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Wrong Captcha!")]
public ActionResult ExampleAction(ExampleModel model)
{
  if (!ModelState.IsValid)
  {
    // TODO: Captcha validation failed, show error message
  }
  else
  {
    // TODO: captcha validation succeeded; execute the protected action

    // Reset the captcha if your app's workflow continues with the same view
    MvcCaptcha.ResetCaptcha("ExampleCaptcha");
  }

Step-4) Configuring the Other ASP.NET Captcha Options

All BotDetect ASP.NET CAPTCHA Traditional API configuration options are described in the Traditional API configuration options page.

Current BotDetect Versions