ASP.NET MVC 6 Basic CAPTCHA C# Code Example

The ASP.NET MVC 6 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 Component and run this example

→ ASP.NET MVC version:

→ .NET programming language:

  • C#

Installed Location

By default, the .NET 4.6 C# version of the ASP.NET MVC 6 Basic Captcha example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET-CORE\WebApp\TraditionalAPI\Mvc6BasicCaptchaExample\

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 CAPTCHA Component > ASP.NET > ASP.NET Core on .NET Core 1.x 2.x Examples > Run .NET Core on .NET Core 1.x 2.x Examples


@* 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:<
                @{ var exampleCaptcha = new MvcCaptcha("ExampleCaptcha") { UserInputID = "CaptchaCode" }; }
                <captcha mvc-captcha="exampleCaptcha" />
                <div class="actions">
                    <input asp-for="CaptchaCode" />
                    <input type="submit" value="Validate" />
                    <span asp-validation-for="CaptchaCode"></span>
                    @if (ViewContext.IsPost() && ViewData.ModelState.IsValid)
                        <span class="correct">Correct!</span>

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

We then create a MvcCaptcha instance, and add it to the form by adding the mvc-captcha tag helper with it.

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();

        [CaptchaValidation("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 CaptchaValidation 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)
            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"