Getting Started with the BotDetect ASP.NET CAPTCHA NuGet Package

The BotDetect ASP.NET Captcha NuGet package has been added to your project.

CAPTCHA Integration Instructions

To show a Captcha challenge on the form and check user input during form submission:

ASP.NET MVC 6

  • Locate the ConfigureServices method

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

    Locate the Configure method and add a call to app.UseCaptcha.

    public void Configure(IApplicationBuilder app, 
    IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
      ...
      app.UseSession();
      
      //configure BotDetectCaptcha
      app.UseCaptcha(Configuration);
      ...
    }
    
  • 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 AspNetCoreWebApplicationExample
    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    @addTagHelper "BotDetect.Web.Mvc.CaptchaTagHelper, BotDetect.Web.Mvc"
    
  • In View code: import the BotDetect namespace, include BotDetect styles in page <head>, create a MvcCaptcha object and pass it to the Captcha TagHelper:

    @using BotDetect.Web.Mvc
    […]
    @section header {
        <environment names="Development,Staging,Production">
            <link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"
                  rel="stylesheet" type="text/css" />
    […]
    }
    
    […]
    
    <label asp-for="CaptchaCode">Retype the code from the picture:</label>
    @{ 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>
      }
    </div>
    
    […]
    
  • Check User Input During Form Submission

    Mark the protected Controller action with the CaptchaValidation attribute to include Captcha validation in ModelState.IsValid checks:
    using BotDetect.Web.Mvc;
      
      […]
    
    [HttpPost]
    [AllowAnonymous]
    [CaptchaValidation("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA code!")]
    public ActionResult ExampleAction(ExampleModel model)
    {
        if (!ModelState.IsValid)
        {  
          // TODO: Captcha validation failed, show error message      
        }  
        else
        {  
          // TODO: Captcha validation passed, proceed with protected action  
    	MvcCaptcha.ResetCaptcha("ExampleCaptcha");			
        }  
    

Detailed ASP.NET MVC integration instructions can be found in the ASP.NET MVC Captcha integration guide.

ASP.NET MVC

In View code: import the BotDetect namespace, include BotDetect styles in page , create a MvcCaptcha object and pass it to the Captcha HtmlHelper:

@using BotDetect.Web.Mvc;

  […]

  <link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"
    rel="stylesheet" type="text/css" />
</head>

  […]

@{ MvcCaptcha exampleCaptcha = new MvcCaptcha("ExampleCaptcha"); }
@Html.Captcha(exampleCaptcha)
@Html.TextBox("CaptchaCode")

Exclude BotDetect paths from ASP.NET MVC Routing:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // BotDetect requests must not be routed
    routes.IgnoreRoute("{*botdetect}", 
      new { botdetect = @"(.*)BotDetectCaptcha\.ashx" });

Check User Input During Form Submission

Mark the protected Controller action with the CaptchaValidation attribute to include Captcha validation in ModelState.IsValid checks:
using BotDetect.Web.Mvc;
  
  […]

[HttpPost]
[AllowAnonymous]
[CaptchaValidation("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA code!")]
public ActionResult ExampleAction(ExampleModel model)
{
    if (!ModelState.IsValid)
    {  
      // TODO: Captcha validation failed, show error message      
    }  
    else
    {  
      // TODO: Captcha validation passed, proceed with protected action  
	MvcCaptcha.ResetCaptcha("ExampleCaptcha");			
    }  

Detailed ASP.NET MVC integration instructions can be found in the ASP.NET MVC Captcha integration guide.

ASP.NET WebForms

On the ASP.NET form you want to protect against bots, add:

<BotDetect:Captcha ID="ExampleCaptcha" runat="server" />
<asp:TextBox ID="CaptchaCodeTextBox" runat="server" />

When the form is submitted, the Captcha validation result must be checked:

if (IsPostBack)
{
    // validate the Captcha to check we're not dealing with a bot
    bool isHuman = ExampleCaptcha.Validate(CaptchaCodeTextBox.Text);
    
    CaptchaCodeTextBox.Text = null; // clear previous user input

    if (!isHuman)
    {
      // TODO: Captcha validation failed, show error message  
    }
    else
    {
      // TODO: Captcha validation passed, proceed with protected action  
    }
}

Detailed ASP.NET WebForms integration instructions can be found in the ASP.NET WebForms Captcha integration guide.

ASP.NET CAPTCHA Code Examples Download

Captcha code examples (ASP.NET WebForms integration examples, ASP.NET MVC integration examples, BotDetect configuration examples - with both C# and VB.NET and ASPX/Razor variants), as well as equivalents for older .NET framework versions and additional resources are included in the BotDetect setup package which can be downloaded from the BotDetect Captcha download page.

BotDetect ASP.NET Captcha Free Download

BotDetect CAPTCHA Documentation

The full index of available BotDetect ASP.NET CAPTCHA documentation can be found on the BotDetect documentation page.