ASP.NET MVC 4.0 Basic CAPTCHA VB.NET Razor Code Example

The ASP.NET MVC 4.0 Basic Captcha VB.NET Razor 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.vbhtml, and the ASP.NET MVC Controller code checking user input is in Controllers/ExampleController.vb.

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

→ ASP.NET MVC version:

→ .NET programming language:

  • C#
  • VB.NET

→ View engine:

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

This example is in the <BDC-DIR>/lgcy-on-lgcy/examples/t_api-captcha-mvc4-api_basics/aspx/vbnet/ folder; and contains the following files:

Views\Example\Index.vbhtml

@* namespaces needed to access BotDetect members *@
@Imports BotDetect.Web.Mvc
@Code
  Layout = Nothing
End Code

<!DOCTYPE html>

<html>
<head runat="server">
  <meta name="viewport" content="width=device-width" />
  <title>BotDetect CAPTCHA Basic ASP.NET MVC 4.0 Example</title>
  <link href="@Url.Content("~/Style/Sheet.css")" rel="stylesheet" 
  type="text/css" />
  <link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl" 
  rel="stylesheet" type="text/css" />
</head>
<body>
  <h1>BotDetect CAPTCHA Basic ASP.NET MVC 4.0 Example</h1>
  @Using Html.BeginForm()
    @<fieldset>
      <legend>CAPTCHA Protection Shown on an ASP.NET MVC View</legend>
      <div>
        @Html.Label("CaptchaCode", "Retype the code from the picture:")
        @Code Dim exampleCaptcha As MvcCaptcha = New MvcCaptcha("ExampleCaptcha")
    exampleCaptcha.UserInputID = "CaptchaCode" 
        End Code
        @Html.Captcha(exampleCaptcha)
      </div>
      <div class="actions">
        @Html.TextBox("CaptchaCode")
        <input type="submit" value="Validate" />
        @Html.ValidationMessage("CaptchaCode")
      </div>
    </fieldset>
  End Using
</body>
</html>

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 calling the Html.Captcha() Html helper with it.

In this simplest case, we also use the Html.ValidationMessage helper to display Captcha validation errors.

Controllers\ExampleController.vb

Imports BotDetect.Web.Mvc
Imports System.Web.Mvc

Namespace AspNetMvc40BasicCaptchaExampleRazorVBNet
  Public Class ExampleController
    Inherits System.Web.Mvc.Controller

    '
    ' GET: /Example

    Function Index() As ActionResult
      Return View()
    End Function


    '
    ' POST: /Example/

    <HttpPost()> _
    <CaptchaValidationActionFilter("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA code!")> _
    Public Function Index(ByVal model As ExampleModel) As ActionResult
      MvcCaptcha.ResetCaptcha("ExampleCaptcha")
      Return View(model)
    End Function

  End Class
End Namespace

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 Html.ValidationMessage helper on the form will then display this error when Captcha validation fails.

App_Start\RouteConfig.vb

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Mvc
Imports System.Web.Routing

Public Class RouteConfig
  Public Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

    ' BotDetect requests must not be routed
    routes.IgnoreRoute("{*botdetect}", 
    New With {.botdetect = "(.*)BotDetectCaptcha\.ashx"})

    routes.MapRoute( _
        name:="Default", _
        url:="{controller}/{action}/{id}", _
        defaults:=New With {.controller = "Example", .action = "Index", .
        id = UrlParameter.Optional} _
    )
  End Sub
End Class

We configure ASP.NET Routing to ignore BotDetect requests, since they do not conform to any MVC-related patterns. The regex defining requests to ignore must match the path configured for the BotDetect HttpHandler registered in web.config.

Web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please 
  visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <section name="botDetect" requirePermission="false" 
    type="BotDetect.Configuration.BotDetectConfigurationSection, BotDetect"/>
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <httpRuntime targetFramework="4.5" />
    <compilation debug="false" targetFramework="4.5" />
    <!-- make sure Session State is enabled -->
    <pages enableSessionState="true">
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <!-- configure Session State for BotDetect use -->
    <sessionState mode="InProc" cookieless="AutoDetect" timeout="20" 
    sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
    <httpHandlers>
      <!-- register HttpHandler used for BotDetect Captcha requests -->
      <add verb="GET" path="BotDetectCaptcha.ashx" 
      type="BotDetect.Web.CaptchaHandler, BotDetect"/>
    </httpHandlers>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,
      HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" 
      scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.
      dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" 
      responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,
      HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" 
      scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.
      30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,
      bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,
      HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.
      TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      <!-- register HttpHandler used for BotDetect Captcha requests -->
      <remove name="BotDetectCaptchaHandler"/>
      <add name="BotDetectCaptchaHandler" preCondition="integratedMode" 
      verb="GET" path="BotDetectCaptcha.ashx" 
      type="BotDetect.Web.CaptchaHandler, BotDetect"/>
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" 
        publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <botDetect helpLinkEnabled="true" helpLinkMode="image" />
</configuration>

To allow the application to use BotDetect Captcha protection, we must enable and configure sessionState, and register the BotDetect HttpHandler in both <system.web><httpHandlers> and <system.webServer><handlers> configuration sections.

The <dependentAssembly> entry for System.Web.Mvc is also needed to make all ASP.NET MVC dependencies referenced by the BotDetect MVC assembly point to the correct ASP.NET MVC version.