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/Home/Index.cshtml, and the ASP.NET MVC Controller code checking user input is in Controllers/HomeController.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\.NET4.6+.NETCORE\WebApp\AspNetCoreWebApplicationExample\

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

Views\Home\Index.cshtml

@* namespaces needed to access BotDetect members *@
@using BotDetect.Web.Mvc
@model AspNetCoreWebApplicationExample.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="Home" 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>
                @{ var exampleCaptcha = new MvcCaptcha("ExampleCaptcha", 
                ViewContext.Current()) { 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>
                    }
                </div>
            </div>
        </fieldset>
    </form>
</div>


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.

Controllers\HomeController.cs

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

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


        [HttpPost]
        [CaptchaValidation("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 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.

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 AspNetCoreWebApplicationExample
{
    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)
        {
            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("/Home/Error");
            }
            app.UseSession();
            app.UseStaticFiles();

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

appsettings.json

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

}