How To Add BotDetect CAPTCHA Protection to ASP.NET MVC Core 1/2 Applications



BotDetect ASP.NET Core Captcha protection can be added to your ASP.NET MVC 6 applications using the MvcCaptcha class, a BotDetect TagHelper and a custom ActionFilterAttribute implemented in the BotDetect.Web.Mvc.dll assembly.

First Time Here?

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

You can also see how BotDetect Captcha protection has been added to the starting ASP.NET MVC application by running the BotDetect Captcha ASP.NET MVC integration code examples coming with the BotDetect installation.

You can reuse the example projects source code that fits your application requirements.

CAPTCHA Integration Steps

When adding BotDetect CAPTCHA to an ASP.NET MVC Core application:
  1. Display a Captcha challenge on the Asp.Net MVC View
  2. Check is the visitor a human in the Controller action
  3. Further Captcha customization and options

I. Display a CAPTCHA Challenge on the ASP.NET MVC View

Before protecting a Controller action in your ASP.NET MVC application with BotDetect Captcha, you should decide how to call the Captcha instance and the related textbox you will use. In this guide, we will use ExampleCaptcha and CaptchaCode. If you plan to protect multiple Controller actions within the same ASP.NET MVC application, you should take care to give each Captcha instance a different name (e.g. LoginCaptcha, RegisterCaptcha, CommentCaptcha etc.).

Add BotDetect Captcha NuGet Package

ASP.NET MVC Core applications should reference both the base BotDetect.dll assembly and the ASP.NET MVC-specific BotDetect.Web.Mvc.dll assembly by adding package CAPTCHA (ASP.NET Core applications running on .NET Core Frameworks) or CAPTCHA.asp.net.core.on.legacy.net.frameworks (ASP.NET Core applications running on the legacy .NET (non-Core) Frameworks) via nuget.org package source. If you don't want to access Microsoft package manager, you need to set up your own offline local NuGet repository. To hosting your own NuGet feeds, please click here for more details.

Configure Your ASP.NET Application Startup

In order to make BotDetect works properly, you need to modify the Startup class which configures the request pipeline that handles all BotDetect Captcha requests made to the application.

Additionally, BotDetect Captcha ASP.NET Core validation requires ASP.NET Session midlleware – generated random Captcha codes have to be stored on the server and compared to the user input.


  • Add the highlighted lines into your app's Startup class (Startup.cs):
public class Startup
{
  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  {
    ...

    // configures Session middleware
    app.UseSession();

    // configure your application pipeline to use Captcha middleware
    app.UseCaptcha(Configuration);

    ...
  }

  // This method gets called by the runtime. Use this method to add services to the container.
  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;
    });
  }
}
  • Add @addTagHelper directive makes Tag Helpers available to the view. To expose BotDetect Captcha Tag Helper in your project, you would use the following in Views/_ViewImports.cshtml file:
    @using AspNetMvc6BasicCaptchaExample
    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    @addTagHelper "BotDetect.Web.Mvc.CaptchaTagHelper, BotDetect.Web.Mvc"
    

Use <captcha> tag helper to display Captcha in the view

BotDetect ASP.NET Core Captcha provides <captcha> tag helper to add Captcha in your forms. The forms also need a <input ⁄> tag in which the user is to type the Captcha code:


  […]

<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.ToUpper() == "POST") && ViewData.ModelState.IsValid)
  {
    <span class="correct">Correct!</span>
  }
</div>

Include the BotDetect CAPTCHA Layout StyleSheet

Since the Html markup generated by BotDetect includes a number of different elements (the Captcha image, the icons for Captcha reloading and Captcha sound playing, the Captcha help link etc.), there are some CSS declarations which need to be included for those elements to display correctly.

The best place to include CSS style declarations is in the page <head>, and since you are controlling the View markup, you know best where exactly to add them. The BotDetect layout stylesheet can be included with the following declaration:

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

If your View generates its own <head> section, you can add these declaration directly in View code. If you're using a Razor Layout and individual Views only generate main content, you can add them to the Razor Layout.

Even better, your layout can include a @RenderSection() – and then individual Views can add their required declarations there without affecting other Views.

Once all of these steps have been performed, the Captcha should be displayed when you open your form in a browser:

BotDetect CAPTCHA added to an ASP.NET form

If the Captcha image isn't being rendered properly, please check the BotDetect integration FAQ.

II. Check is the Visitor a Human in the Controller Action

Once the Captcha challenge is displayed on your View, the Controller code processing submissions can check if the Captcha was solved successfully and deny access to bots.

Captcha validation is encapsulated within an ActionFilterAttribute that can be added to actions accepting HtppVerbs.Post requests; the CaptchaValidationActionFilter attribute just needs to be passed the names of the Captcha instance and Captcha code textbox used. ASP.NET Session state must also be enabled before Captcha validation can work.

Mark the Protected Controller Action with the CaptchaValidationActionFilter Attribute

The CaptchaValidationActionFilter attribute takes three parameters:

  • Captcha code textbox name
  • MvcCaptcha instance name
  • the error message that will be displayed when Captcha validation fails

//
// POST: /ExampleController/ExampleAction

[HttpPost]
[AllowAnonymous]
[CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA code!")]
public ActionResult ExampleAction(ExampleModel model)
{
    if (ModelState.IsValid)
    {    
    
        […]
        
        // You should call ResetCaptcha as demonstrated in the following example.
         MvcCaptcha.ResetCaptcha("ExampleCaptcha");

        […]
    

If everything has been configured correctly, the above ActionFilterAttribute will automatically add the appropriate ModelState error when Captcha validation fails, and checking ModelState validity will include the Captcha validation result.

III. Further CAPTCHA Customization and Options

BotDetect ASP.NET Captcha allows detailed customization of many Captcha properties, and you can read more about them in the BotDetect Captcha configuration How To.