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:

Views\Example\Index.cshtml

@* 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" />
    </environment>
}
@{
    ViewData["Title"] = "Basic ASP.NET Core Web Application CAPTCHA Code 
    Example";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<div class="column">
    <h1>
        BotDetect ASP.NET CAPTCHA Validation: <br /> Basic ASP.NET Core Web 
        Application CAPTCHA Code Example
    </h1>
    <form asp-controller="Example" asp-action="Index" method="post">
        <fieldset>
            <legend>ASP.NET MVC CAPTCHA Validation</legend>
            <div>
                <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>
            </div>
        </fieldset>
    </form>
</div>


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.

Controllers\ExampleController.cs

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

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


        [HttpPost]
        [CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Incorrect!")]
        public IActionResult Index(ExampleModel model)
        {
            
           MvcCaptcha.ResetCaptcha("ExampleCaptcha");
            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.

Startup.cs

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()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: 
                true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:
                true)
                .AddEnvironmentVariables();

            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.AddMvc();
            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)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Example/Error");
            }
            app.UseSession();
            app.UseStaticFiles();

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

appsettings.json

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

}