ASP.NET MVC Core 1/2 Basic CAPTCHA C# Code Example

The ASP.NET MVC Core Basic Captcha C# 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 Quickstart for key integration steps.

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

Download the BotDetect ASP.NET CAPTCHA Generator archive to run this example

→ ASP.NET MVC version:

→ .NET programming language:

  • C#

Within this page, the root folder of the extracted archive is referred as the <BDC-DIR>.

This example is in the <BDC-DIR>/core-on-core/examples/t_api-captcha-mvccore2-api_basics/ folder; and contains the following files:


@* namespaces needed to access BotDetect members *@
@using BotDetect.Web.Mvc
@model AspNetMvc6BasicCaptchaExample.Models.ExampleModel
@section header {
    <environment names="Development,Staging,Production">
        <link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"
              rel="stylesheet" type="text/css" />
        <link rel="stylesheet" href="~/css/StyleSheet.css" />
    ViewData["Title"] = "Basic ASP.NET Core Web Application CAPTCHA Code 

<div class="column">
        BotDetect ASP.NET CAPTCHA Validation: <br /> Basic ASP.NET Core Web 
        Application CAPTCHA Code Example
    <form asp-controller="Example" asp-action="Index" method="post">
            <legend>ASP.NET MVC CAPTCHA Validation</legend>
                <label asp-for="CaptchaCode">Retype the code from the picture:<
                <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>

To display Captcha protection on the example View, we use <captcha> tag helper which generates the Html markup required to show the Captcha image and the Captcha sound / reload buttons.

In this simplest case, we also use the asp-validation-for tag helper to display Captcha validation errors.


using AspNetMvc6BasicCaptchaExample.Models;
using BotDetect.Web.Mvc;
using Microsoft.AspNetCore.Mvc;

namespace AspNetMvc6BasicCaptchaExample.Controllers
    public class ExampleController : Controller
        public IActionResult Index()
            return View();

        [CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Incorrect!")]
        public IActionResult Index(ExampleModel model)
            return View(model);

        public IActionResult Error()
            return View();

After we've included the BotDetect.Web.Mvc namespace, we just need to add the CaptchaValidationActionFilter 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 Captcha instance we're validating (which we set to ExampleCaptcha in the MvcCaptcha constructor), 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 form is submitted, and will automatically add a Model error with the error message configured above when Captcha validation fails. The asp-validation-for tag helper on the form will then display this error when Captcha validation fails.


using System;
using BotDetect.Web;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace AspNetMvc6BasicCaptchaExample
    public class Startup
        public Startup(IHostingEnvironment env)
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: 
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:

            Configuration = builder.Build();

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add 
        services to the container.
        public void ConfigureServices(IServiceCollection services)
            // Uncomment the next line if the .NET Core 1.x compatibility is required
            // services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddMemoryCache(); // Adds a default in-memory 
           // implementation of IDistributedCache
            // Add framework services.
            services.AddSession(options =>
                options.IdleTimeout = TimeSpan.FromMinutes(20);

        // This method gets called by the runtime. Use this method to configure 
        the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
        ILoggerFactory loggerFactory)

            if (env.IsDevelopment())

            //configure BotDetectCaptcha
            app.UseMvc(routes =>
                routes.MapRoute(name: "areaRoute",
       template: "{area:exists}/{controller=Example}/{action=Index}");
                    name: "default",
                    template: "{controller=Example}/{action=Index}/{id?}");


    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
    "BotDetect": {
        "HelpLinkEnabled": true,
        "HelpLinkMode": "image"