ASP.NET Website Razor 3 CAPTCHA C# Code Example

The ASP.NET Website Razor 3 Captcha example project shows the most basic source code required to protect an ASP.NET Web Pages form using new Razor syntax with BotDetect CAPTCHA and validate the user input.

First Time Here?

Check the BotDetect Developer Crash Course for key integration steps.

ASP.NET Website Razor 3 code displaying CAPTCHA protection and checking user input can be found in Register.cshtml.

Download the BotDetect ASP.NET CAPTCHA Component and run this example
  • C#
  • VB.NET

Visual Studio 2015 / .NET 4.6

By default, the VB.NET 4.6 version of the ASP.NET Website Razor 3 Captcha example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET4.6\WebApp\AspNetWebSiteRazor3CaptchaExample\VBNet

You can also run it from the BotDetect Start Menu:
Programs > Captcha Inc > BotDetect 4 CAPTCHA Component > ASP.NET > DotNET 4.6 Web Applications > Run

Register.cshtml

@Imports BotDetect.Web
@* Remove this section if you are using bundling *@
@Section Scripts
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
End Section

@Code
    Layout = "~/_SiteLayout.vbhtml"
    PageData("Title") = "Register"

    ' Initialize general page variables
    Dim email As String = ""
    Dim password As String = ""
    Dim confirmPassword As String = ""

    ' Setup validation
    Validation.RequireField("email", "The email address field is required.")
    Validation.RequireField("password", "Password cannot be blank.")
    Validation.Add("confirmPassword",
        Validator.EqualsTo("password", "Password and confirmation password 
        do not match."))
    Validation.Add("password",
        Validator.StringLength(
            maxLength:=Int32.MaxValue,
            minLength:=6,
            errorMessage:="Password must be at least 6 characters"))

    Dim exampleCaptcha As Captcha = New Captcha("ExampleCaptcha")
    exampleCaptcha.UserInputID = "CaptchaCode"
    exampleCaptcha.RemoteScriptEnabled = True

    ' If this is a POST request, validate and process data
    If IsPost Then
        AntiForgery.Validate()
        email = Request.Form("email")
        password = Request.Form("password")
        confirmPassword = Request.Form("confirmPassword")

        Dim isHuman As Boolean = exampleCaptcha.Validate()
        If (Not isHuman) Then
            ModelState.AddFormError("Captcha response was not correct.")
        End If

        ' If all information is valid, create a new account
        If Validation.IsValid() Then
            ' Insert a new user into the database
            Dim db As Database = Database.Open("StarterSite")

            ' Check if user already exists
            Dim user As Object = db.QuerySingle("SELECT Email FROM 
            UserProfile WHERE LOWER(Email) = LOWER(@0)", email)
            If user Is Nothing Then
                ' Insert email into the profile table
                db.Execute("INSERT INTO UserProfile (Email) VALUES (@0)", 
                email)

                ' Create and associate a new entry in the membership 
                database.
                ' If successful, continue processing the request
                Try
                    Dim requireEmailConfirmation As Boolean = Not WebMail.
                    SmtpServer.IsEmpty()
                    Dim token As String = WebSecurity.CreateAccount(email, 
                    password, requireEmailConfirmation)
                    If requireEmailConfirmation Then
                        Dim hostUrl As String = Request.Url.GetComponents(
                        UriComponents.SchemeAndServer, UriFormat.Unescaped)
                        Dim confirmationUrl As String = hostUrl + 
                        VirtualPathUtility.ToAbsolute(
                        "~/Account/Confirm?confirmationCode=" + HttpUtility.
                        UrlEncode(token))

                        WebMail.Send(
                            to:=email,
                            subject:="Please confirm your account",
                            body:="Your confirmation code is: " + token + ".
                            Visit <a href=""" + confirmationUrl + """>" + 
                            confirmationUrl + "</a> to activate your 
                            account."
                        )
                    End If

                    If requireEmailConfirmation Then
                        ' Thank the user for registering and let them know 
                        an email is on its way
                        Response.Redirect("~/Account/Thanks")
                    Else
                        ' Navigate back to the homepage and exit
                        WebSecurity.Login(email, password)

                        Response.Redirect("~/")
                    End If
                Catch e As System.Web.Security.
                MembershipCreateUserException
                    ModelState.AddFormError(e.Message)
                End Try
            Else
                ' User already exists
                ModelState.AddFormError("Email address is already in use.")
            End If
        End If
    End If
End Code

<hgroup class="title">
    <h1>@PageData("Title").</h1>
    <h2>Create a new account.</h2>
</hgroup>

<form method="post">
    @AntiForgery.GetHtml()
    @* If at least one validation error exists, notify the user *@
    @Html.ValidationSummary("Account creation was unsuccessful. Please 
    correct the errors and try again.", excludeFieldErrors:=True, 
    htmlAttributes:=Nothing)

    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li class="email">
                <label for="email" @If Not ModelState.IsValidField("email") 
                Then @<text> class="error-label" </text>  End If>Email 
                address</label>
                <input type="text" id="email" name="email" value="@email" 
                @Validation.For("email") />
                @* Write any email validation errors to the page *@
                @Html.ValidationMessage("email")
            </li>
            <li class="password">
                <label for="password" @If Not ModelState.IsValidField(
                "password") Then @<text> class="error-label" </text>  End 
                If>Password</label>
                <input type="password" id="password" name="password" 
                @Validation.For("password") />
                @* Write any password validation errors to the page *@
                @Html.ValidationMessage("password")
            </li>
            <li class="confirm-password">
                <label for="confirmPassword" @If Not ModelState.
                IsValidField("confirmPassword") Then @<text> class="error-
                label" </text>  End If>Confirm password</label>
                <input type="password" id="confirmPassword" 
                name="confirmPassword" @Validation.For("confirmPassword") />
                @* Write any password validation errors to the page *@
                @Html.ValidationMessage("confirmPassword")
            </li>
            <li>
                @Html.Label("Retype the code from the picture:", 
                "CaptchaCode")
                @Html.Raw(exampleCaptcha.Html)
                @Html.TextBox("CaptchaCode")

            </li>
        </ol>
        <input type="submit" value="Register" />
    </fieldset>
</form>

Web.config

<?xml version="1.0" encoding="utf-8"?>

<configuration>
    <configSections>
        <section name="botDetect" requirePermission="false" 
        type="BotDetect.Configuration.BotDetectConfigurationSection, BotDetect"/>
    </configSections>
    <system.web>
        <compilation debug="true" targetFramework="4.6"/>
        <httpRuntime targetFramework="4.6"/>
        <httpHandlers>
            <!-- Register the HttpHandler used for BotDetect Captcha requests -->
            <add verb="GET" path="BotDetectCaptcha.ashx" 
            type="BotDetect.Web.CaptchaHandler, BotDetect"/>
        </httpHandlers>
        <!-- Register a custom SessionIDManager for BotDetect Captcha requests -->
        <sessionState mode="InProc" cookieless="AutoDetect" timeout="20" 
        sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
    </system.web>

    <connectionStrings>
        <add name="StarterSite" connectionString="Data 
        Source=|DataDirectory|\StarterSite.sdf" providerName="System.Data.
        SqlServerCe.4.0"/>
    </connectionStrings>

    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="DotNetOpenAuth.Core" 
                publicKeyToken="2780ccd10d57b246"/>
                <bindingRedirect oldVersion="1.0.0.0-4.1.0.0" newVersion="4.
                1.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="DotNetOpenAuth.AspNet" 
                publicKeyToken="2780ccd10d57b246"/>
                <bindingRedirect oldVersion="1.0.0.0-4.1.0.0" newVersion="4.
                1.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Optimization" 
                publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.
                1.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="WebGrease" 
                publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234.0.0" 
                newVersion="1.5.2.14234.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Helpers" 
                publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.
                0.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages" 
                publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.
                0.0.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
    <system.data>
        <DbProviderFactories>
            <remove invariant="System.Data.SqlServerCe.4.0"/>
            <add name="Microsoft SQL Server Compact Data Provider 4.0" 
            invariant="System.Data.SqlServerCe.4.0"
                    description=".NET Framework Data Provider for Microsoft 
                    SQL Server Compact"
                    type="System.Data.SqlServerCe.SqlCeProviderFactory, 
                    System.Data.SqlServerCe, Version=4.0.0.0, 
                    Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
        </DbProviderFactories>
    </system.data>
    <system.codedom>
        <compilers>
            <compiler language="c#;cs;csharp" extension=".cs"
            type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.
            CSharpCodeProvider, Microsoft.CodeDom.Providers.
            DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, 
            PublicKeyToken=31bf3856ad364e35"
            warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;
            1699;1701"/>
            <compiler language="vb;vbs;visualbasic;vbscript" extension=".
            vb"
            type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.
            VBCodeProvider, Microsoft.CodeDom.Providers.
            DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, 
            PublicKeyToken=31bf3856ad364e35"
            warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 
            /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
        </compilers>
    </system.codedom>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <handlers>
            <!-- Register the HttpHandler used for BotDetect Captcha requests (IIS 7.0+) -->
            <remove name="BotDetectCaptchaHandler"/>
            <add name="BotDetectCaptchaHandler" 
            preCondition="integratedMode" verb="GET" 
            path="BotDetectCaptcha.ashx" type="BotDetect.Web.CaptchaHandler, BotDetect"/>
        </handlers>
    </system.webServer>
    <botDetect helpLinkEnabled="true" helpLinkMode="image"/>
</configuration>