Use THIS nuget in:
- ASP.NET applications running on the legacy .NET (non-Core) Frameworks
- ASP.NET Core applications running on the .NET Core Frameworks
1. Add CAPTCHA NuGet Package
Use THIS nuget in:
- ASP.NET Core applications running on the legacy .NET (non-Core) Frameworks
1. Add CAPTCHA.asp.net.core.on.legacy.net.frameworks NuGet Package
-
Open the NuGet Package Manager.
-
Choose nuget.org package source and search for CAPTCHA.asp.net.core.on.legacy.net.frameworks.
-
Install the CAPTCHA.asp.net.core.on.legacy.net.frameworks package. This should add a line to you project.json similar to the one shown below.
"dependencies": {
...
"CAPTCHA.asp.net.core.on.legacy.net.frameworks": "4.4.1"
}
2. Configure Your ASP.NET Application
- Add the highlighted lines into your app's
Startup class (Startup.cs):
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// configures Session middleware
app.UseSession();
// configure your application pipeline to use Captcha middleware
app.UseCaptcha(Configuration);
...
}
// 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();
// Add Session services.
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
});
}
}
-
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 AspNetMvc6BasicCaptchaExample
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "BotDetect.Web.Mvc.CaptchaTagHelper, BotDetect.Web.Mvc"
3. Show a Captcha Challenge on the Form
In View code: include BotDetect styles in page
<head>, and show Captcha challage on the form using
captcha tag helper:
[…]
@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>
<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>
[…]
4. 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");
}
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
using BotDetect.Web.Mvc;
[…]
[HttpPost]
[AllowAnonymous]
public ActionResult ExampleAction(ExampleModel model)
{
// init mvcCaptcha instance with captchaId
MvcCaptcha mvcCaptcha = new MvcCaptcha("ExampleCaptcha");
// get user input value
string userInput = HttpContext.Request.Form["CaptchaCode"];
// get validatingInstanceId from HttpContext.Request.Form
string validatingInstanceId = HttpContext.Request.Form[mvcCaptcha.ValidatingInstanceKey];
// or get validatingInstanceId from above mvcCaptcha instance
//string validatingInstanceId = mvcCaptcha.WebCaptcha.ValidatingInstanceId;
// call the built-in Validate method from above MvcCaptcha instance.
if (mvcCaptcha.Validate(userInput, validatingInstanceId))
{
// or you can use static Validate method of MvcCaptcha class
(i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
}
else
{
ModelState.AddModelError("CaptchaCode", "Incorrect!");
}
return View(model);
}
[back to top]
ASP.NET MVC 5 CAPTCHA / C#
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, 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");
exampleCaptcha.UserInputID = "CaptchaCode";}
@Html.Captcha(exampleCaptcha)
@Html.TextBox("CaptchaCode")
3. 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");
}
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
using BotDetect.Web.Mvc;
[…]
[HttpPost]
[AllowAnonymous]
public ActionResult ExampleAction(ExampleModel model)
{
// init mvcCaptcha instance with captchaId
MvcCaptcha mvcCaptcha = new MvcCaptcha("ExampleCaptcha");
// get user input value
string userInput = HttpContext.Request.Form["CaptchaCode"];
// get validatingInstanceId from HttpContext.Request.Form
string validatingInstanceId = HttpContext.Request.Form[mvcCaptcha.ValidatingInstanceKey];
// or get validatingInstanceId from above mvcCaptcha instance
//string validatingInstanceId = mvcCaptcha.WebCaptcha.ValidatingInstanceId;
// call the built-in Validate method from above MvcCaptcha instance.
if (mvcCaptcha.Validate(userInput, validatingInstanceId))
{
// or you can use static Validate method of MvcCaptcha class
(i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
}
else
{
ModelState.AddModelError("CaptchaCode", "Incorrect!");
}
return View(model);
}
4. Configure Your ASP.NET Application
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" });
Update your application configuration (the
web.config file):
<system.web>
<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>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 5 CAPTCHA / VB.NET
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, create a
MvcCaptcha object and pass it to the Captcha
HtmlHelper:
@Imports BotDetect.Web.Mvc
[…]
<link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"
rel="stylesheet" type="text/css" />
</head>
[…]
@Code Dim exampleCaptcha As MvcCaptcha = New MvcCaptcha("ExampleCaptcha")
exampleCaptcha.UserInputID = "CaptchaCode" End Code
@Html.Captcha(exampleCaptcha)
@Html.TextBox("CaptchaCode")
3. Check User Input During Form Submission
Mark the protected Controller action with the
CaptchaValidation attribute to include Captcha validation in
ModelState.IsValid checks:
Imports System.Web.Mvc
[…]
<HttpPost()> _
<CaptchaValidation("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA Code!")> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
If ModelState.IsValid Then
' TODO: Captcha validation failed, show error message
Else
' TODO: Captcha validation passed, proceed with protected action
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
Imports System.Web.Mvc
[…]
<HttpPost()> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
' init mvcCaptcha instance with captchaId
Dim mvcCaptcha = New MvcCaptcha("ExampleCaptcha")
' get user input value
Dim userInput As String = HttpContext.Request.Form("CaptchaCode")
' get validatingInstanceId from HttpContext.Request.Form
Dim validatingInstanceId As String = HttpContext.Request.Form(mvcCaptcha.ValidatingInstanceKey)
' or get validatingInstanceId from above mvcCaptcha instance
' Dim validatingInstanceId As String = mvcCaptcha.WebCaptcha.ValidatingInstanceId
' call the built-in Validate method from above MvcCaptcha instance.
If (mvcCaptcha.Validate(userInput, validatingInstanceId)) Then
' or you can use static Validate method of MvcCaptcha class (i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
mvcCaptcha.ResetCaptcha("ExampleCaptcha")
Else
ModelState.AddModelError("CaptchaCode", "Incorrect!")
End If
Return View(model)
4. Configure Your ASP.NET Application
Exclude BotDetect paths from ASP.NET MVC Routing:
Public 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"})
Update your application configuration (the
web.config file):
<system.web>
<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>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 4 CAPTCHA / C# / ASPX
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, create a
MvcCaptcha object and pass it to the Captcha
HtmlHelper:
<%@ Import Namespace="BotDetect.Web.Mvc" %>
[…]
<link href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>"
rel="stylesheet" type="text/css" />
</head>
[…]
<% MvcCaptcha exampleCaptcha = new MvcCaptcha("ExampleCaptcha");
exampleCaptcha.UserInputID = "CaptchaCode"; %>
<%: Html.Captcha(exampleCaptcha) %>
@Html.TextBox("CaptchaCode")
3. 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");
}
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
using BotDetect.Web.Mvc;
[…]
[HttpPost]
[AllowAnonymous]
public ActionResult ExampleAction(ExampleModel model)
{
// init mvcCaptcha instance with captchaId
MvcCaptcha mvcCaptcha = new MvcCaptcha("ExampleCaptcha");
// get user input value
string userInput = HttpContext.Request.Form["CaptchaCode"];
// get validatingInstanceId from HttpContext.Request.Form
string validatingInstanceId = HttpContext.Request.Form[mvcCaptcha.ValidatingInstanceKey];
// or get validatingInstanceId from above mvcCaptcha instance
//string validatingInstanceId = mvcCaptcha.WebCaptcha.ValidatingInstanceId;
// call the built-in Validate method from above MvcCaptcha instance.
if (mvcCaptcha.Validate(userInput, validatingInstanceId))
{
// or you can use static Validate method of MvcCaptcha class
(i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
}
else
{
ModelState.AddModelError("CaptchaCode", "Incorrect!");
}
return View(model);
}
4. Configure Your ASP.NET Application
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" });
Update your application configuration (the
web.config file):
<system.web>
<httpHandlers>
<!-- Register the HttpHandler used for BotDetect Captcha
requests -->
<add verb="GET" path="BotDetectCaptcha.ashx"
type="BotDetect.Web.CaptchaHandler, BotDetect"/>
</httpHandlers>
<!-- make sure Session State is enabled -->
<pages enableSessionState="true">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
<!-- Register a custom SessionIDManager for BotDetect Captcha
requests -->
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20"
sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
</system.web>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 4 CAPTCHA / C# / RAZOR
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, 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");
exampleCaptcha.UserInputID = "CaptchaCode"; }
@Html.Captcha(exampleCaptcha)
@Html.TextBox("CaptchaCode")
3. 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");
}
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
using BotDetect.Web.Mvc;
[…]
[HttpPost]
[AllowAnonymous]
public ActionResult ExampleAction(ExampleModel model)
{
// init mvcCaptcha instance with captchaId
MvcCaptcha mvcCaptcha = new MvcCaptcha("ExampleCaptcha");
// get user input value
string userInput = HttpContext.Request.Form["CaptchaCode"];
// get validatingInstanceId from HttpContext.Request.Form
string validatingInstanceId = HttpContext.Request.Form[mvcCaptcha.ValidatingInstanceKey];
// or get validatingInstanceId from above mvcCaptcha instance
//string validatingInstanceId = mvcCaptcha.WebCaptcha.ValidatingInstanceId;
// call the built-in Validate method from above MvcCaptcha instance.
if (mvcCaptcha.Validate(userInput, validatingInstanceId))
{
// or you can use static Validate method of MvcCaptcha class
(i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
}
else
{
ModelState.AddModelError("CaptchaCode", "Incorrect!");
}
return View(model);
}
4. Configure Your ASP.NET Application
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" });
Update your application configuration (the
web.config file):
<system.web>
<httpHandlers>
<!-- Register the HttpHandler used for BotDetect Captcha
requests -->
<add verb="GET" path="BotDetectCaptcha.ashx"
type="BotDetect.Web.CaptchaHandler, BotDetect"/>
</httpHandlers>
<!-- 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>
<!-- Register a custom SessionIDManager for BotDetect Captcha
requests -->
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20"
sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
</system.web>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 4 CAPTCHA / VB.NET / ASPX
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, create a
MvcCaptcha object and pass it to the Captcha
HtmlHelper:
<%@ Import Namespace="BotDetect.Web.Mvc" %>
[…]
<link href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>"
rel="stylesheet" type="text/css" />
</head>
[…]
<% Dim exampleCaptcha As MvcCaptcha = New MvcCaptcha("ExampleCaptcha")
exampleCaptcha.UserInputID = "CaptchaCode"%>
<%: Html.Captcha(exampleCaptcha) %>
<%: Html.TextBox("CaptchaCode") %>
3. Check User Input During Form Submission
Mark the protected Controller action with the
CaptchaValidation attribute to include Captcha validation in
ModelState.IsValid checks:
Imports System.Web.Mvc
[…]
<HttpPost()> _
<CaptchaValidation("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA Code!")> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
If ModelState.IsValid Then
' TODO: Captcha validation failed, show error message
Else
' TODO: Captcha validation passed, proceed with protected action
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
Imports System.Web.Mvc
[…]
<HttpPost()> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
' init mvcCaptcha instance with captchaId
Dim mvcCaptcha = New MvcCaptcha("ExampleCaptcha")
' get user input value
Dim userInput As String = HttpContext.Request.Form("CaptchaCode")
' get validatingInstanceId from HttpContext.Request.Form
Dim validatingInstanceId As String = HttpContext.Request.Form(mvcCaptcha.ValidatingInstanceKey)
' or get validatingInstanceId from above mvcCaptcha instance
' Dim validatingInstanceId As String = mvcCaptcha.WebCaptcha.ValidatingInstanceId
' call the built-in Validate method from above MvcCaptcha instance.
If (mvcCaptcha.Validate(userInput, validatingInstanceId)) Then
' or you can use static Validate method of MvcCaptcha class (i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
mvcCaptcha.ResetCaptcha("ExampleCaptcha")
Else
ModelState.AddModelError("CaptchaCode", "Incorrect!")
End If
Return View(model)
4. Configure Your ASP.NET Application
Exclude BotDetect paths from ASP.NET MVC Routing:
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"})
Update your application configuration (the
web.config file):
<system.web>
<httpHandlers>
<!-- Register the HttpHandler used for BotDetect Captcha
requests -->
<add verb="GET" path="BotDetectCaptcha.ashx"
type="BotDetect.Web.CaptchaHandler, BotDetect"/>
</httpHandlers>
<!-- make sure Session State is enabled -->
<pages enableSessionState="true">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
<!-- Register a custom SessionIDManager for BotDetect Captcha
requests -->
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20"
sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
</system.web>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 4 CAPTCHA / VB.NET / RAZOR
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, create a
MvcCaptcha object and pass it to the Captcha
HtmlHelper:
@Imports BotDetect.Web.Mvc
[…]
<link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"
rel="stylesheet" type="text/css" />
</head>
[…]
@Code Dim exampleCaptcha As MvcCaptcha = New MvcCaptcha("ExampleCaptcha")
exampleCaptcha.UserInputID = "CaptchaCode" End Code
@Html.Captcha(exampleCaptcha)
#64;Html.TextBox("CaptchaCode")
3. Check User Input During Form Submission
Mark the protected Controller action with the
CaptchaValidation attribute to include Captcha validation in
ModelState.IsValid checks:
Imports System.Web.Mvc
[…]
<HttpPost()> _
<CaptchaValidation("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA Code!")> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
If ModelState.IsValid Then
' TODO: Captcha validation failed, show error message
Else
' TODO: Captcha validation passed, proceed with protected action
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
Imports System.Web.Mvc
[…]
<HttpPost()> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
' init mvcCaptcha instance with captchaId
Dim mvcCaptcha = New MvcCaptcha("ExampleCaptcha")
' get user input value
Dim userInput As String = HttpContext.Request.Form("CaptchaCode")
' get validatingInstanceId from HttpContext.Request.Form
Dim validatingInstanceId As String = HttpContext.Request.Form(mvcCaptcha.ValidatingInstanceKey)
' or get validatingInstanceId from above mvcCaptcha instance
' Dim validatingInstanceId As String = mvcCaptcha.WebCaptcha.ValidatingInstanceId
' call the built-in Validate method from above MvcCaptcha instance.
If (mvcCaptcha.Validate(userInput, validatingInstanceId)) Then
' or you can use static Validate method of MvcCaptcha class (i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
mvcCaptcha.ResetCaptcha("ExampleCaptcha")
Else
ModelState.AddModelError("CaptchaCode", "Incorrect!")
End If
Return View(model)
4. Configure Your ASP.NET Application
Exclude BotDetect paths from ASP.NET MVC Routing:
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"})
Update your application configuration (the
web.config file):
<system.web>
<httpHandlers>
<!-- Register the HttpHandler used for BotDetect Captcha
requests -->
<add verb="GET" path="BotDetectCaptcha.ashx"
type="BotDetect.Web.CaptchaHandler, BotDetect"/>
</httpHandlers>
<!-- 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>
<!-- Register a custom SessionIDManager for BotDetect Captcha
requests -->
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20"
sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
</system.web>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 3 CAPTCHA / C#
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, 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");
exampleCaptcha.UserInputID = "CaptchaCode";}
@Html.Captcha(exampleCaptcha)
@Html.TextBox("CaptchaCode")
3. 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");
}
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
using BotDetect.Web.Mvc;
[…]
[HttpPost]
[AllowAnonymous]
public ActionResult ExampleAction(ExampleModel model)
{
// init mvcCaptcha instance with captchaId
MvcCaptcha mvcCaptcha = new MvcCaptcha("ExampleCaptcha");
// get user input value
string userInput = HttpContext.Request.Form["CaptchaCode"];
// get validatingInstanceId from HttpContext.Request.Form
string validatingInstanceId = HttpContext.Request.Form[mvcCaptcha.ValidatingInstanceKey];
// or get validatingInstanceId from above mvcCaptcha instance
//string validatingInstanceId = mvcCaptcha.WebCaptcha.ValidatingInstanceId;
// call the built-in Validate method from above MvcCaptcha instance.
if (mvcCaptcha.Validate(userInput, validatingInstanceId))
{
// or you can use static Validate method of MvcCaptcha class
(i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
}
else
{
ModelState.AddModelError("CaptchaCode", "Incorrect!");
}
return View(model);
}
4. Configure Your ASP.NET Application
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" });
Update your application configuration (the
web.config file):
<system.web>
<httpHandlers>
<!-- Register the HttpHandler used for BotDetect Captcha
requests -->
<add verb="GET" path="BotDetectCaptcha.ashx"
type="BotDetect.Web.CaptchaHandler, BotDetect"/>
</httpHandlers>
<!-- 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>
<!-- Register a custom SessionIDManager for BotDetect Captcha
requests -->
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20"
sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
</system.web>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 3 CAPTCHA / VB.NET
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, create a
MvcCaptcha object and pass it to the Captcha
HtmlHelper:
@Imports BotDetect.Web.Mvc
[…]
<link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"
rel="stylesheet" type="text/css" />
</head>
[…]
@Code Dim exampleCaptcha As MvcCaptcha = New MvcCaptcha("ExampleCaptcha")
exampleCaptcha.UserInputID = "CaptchaCode" End Code
@Html.Captcha(exampleCaptcha)
@Html.TextBox("CaptchaCode")
3. Check User Input During Form Submission
Mark the protected Controller action with the
CaptchaValidation attribute to include Captcha validation in
ModelState.IsValid checks:
Imports System.Web.Mvc
[…]
<HttpPost()> _
<CaptchaValidation("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA Code!")> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
If ModelState.IsValid Then
' TODO: Captcha validation failed, show error message
Else
' TODO: Captcha validation passed, proceed with protected action
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
Imports System.Web.Mvc
[…]
<HttpPost()> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
' init mvcCaptcha instance with captchaId
Dim mvcCaptcha = New MvcCaptcha("ExampleCaptcha")
' get user input value
Dim userInput As String = HttpContext.Request.Form("CaptchaCode")
' get validatingInstanceId from HttpContext.Request.Form
Dim validatingInstanceId As String = HttpContext.Request.Form(mvcCaptcha.ValidatingInstanceKey)
' or get validatingInstanceId from above mvcCaptcha instance
' Dim validatingInstanceId As String = mvcCaptcha.WebCaptcha.ValidatingInstanceId
' call the built-in Validate method from above MvcCaptcha instance.
If (mvcCaptcha.Validate(userInput, validatingInstanceId)) Then
' or you can use static Validate method of MvcCaptcha class (i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
mvcCaptcha.ResetCaptcha("ExampleCaptcha")
Else
ModelState.AddModelError("CaptchaCode", "Incorrect!")
End If
Return View(model)
4. Configure Your ASP.NET Application
Exclude BotDetect paths from ASP.NET MVC Routing:
Public 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"})
Update your application configuration (the
web.config file):
<system.web>
<httpHandlers>
<!-- Register the HttpHandler used for BotDetect Captcha
requests -->
<add verb="GET" path="BotDetectCaptcha.ashx"
type="BotDetect.Web.CaptchaHandler, BotDetect"/>
</httpHandlers>
<!-- 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>
<!-- Register a custom SessionIDManager for BotDetect Captcha
requests -->
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20"
sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
</system.web>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 2 CAPTCHA / C#
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, create a
MvcCaptcha object and pass it to the Captcha
HtmlHelper:
<%@ Import Namespace="BotDetect.Web.Mvc" %>
[…]
<link href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>"
rel="stylesheet" type="text/css" />
</head>
[…]
<% MvcCaptcha exampleCaptcha = new MvcCaptcha("ExampleCaptcha");
exampleCaptcha.UserInputID = "CaptchaCode"; %>
<%: Html.Captcha(exampleCaptcha) %>
@Html.TextBox("CaptchaCode")
3. 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");
}
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
using BotDetect.Web.Mvc;
[…]
[HttpPost]
[AllowAnonymous]
public ActionResult ExampleAction(ExampleModel model)
{
// init mvcCaptcha instance with captchaId
MvcCaptcha mvcCaptcha = new MvcCaptcha("ExampleCaptcha");
// get user input value
string userInput = HttpContext.Request.Form["CaptchaCode"];
// get validatingInstanceId from HttpContext.Request.Form
string validatingInstanceId = HttpContext.Request.Form[mvcCaptcha.ValidatingInstanceKey];
// or get validatingInstanceId from above mvcCaptcha instance
//string validatingInstanceId = mvcCaptcha.WebCaptcha.ValidatingInstanceId;
// call the built-in Validate method from above MvcCaptcha instance.
if (mvcCaptcha.Validate(userInput, validatingInstanceId))
{
// or you can use static Validate method of MvcCaptcha class
(i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
}
else
{
ModelState.AddModelError("CaptchaCode", "Incorrect!");
}
return View(model);
}
4. Configure Your ASP.NET Application
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" });
Update your application configuration (the
web.config file):
<system.web>
<httpHandlers>
<!-- Register the HttpHandler used for BotDetect Captcha
requests -->
<add verb="GET" path="BotDetectCaptcha.ashx"
type="BotDetect.Web.CaptchaHandler, BotDetect"/>
</httpHandlers>
<!-- make sure Session State is enabled -->
<pages enableSessionState="true">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<!-- add BotDetect namespaces for coding convenience -->
<add namespace="BotDetect"/>
<add namespace="BotDetect.Web"/>
<add namespace="BotDetect.Web.UI"/>
<add namespace="BotDetect.Web.Mvc"/>
</namespaces>
</pages>
<!-- Register a custom SessionIDManager for BotDetect Captcha
requests -->
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20"
sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
</system.web>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 2 CAPTCHA / VB.NET
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, create a
MvcCaptcha object and pass it to the Captcha
HtmlHelper:
<%@ Import Namespace="BotDetect.Web.Mvc" %>
[…]
<link href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>"
rel="stylesheet" type="text/css" />
</head>
[…]
<% Dim exampleCaptcha As MvcCaptcha = New MvcCaptcha("ExampleCaptcha")
exampleCaptcha.UserInputID = "CaptchaCode"%>
<%: Html.Captcha(exampleCaptcha) %>
<%: Html.TextBox("CaptchaCode") %>
3. Check User Input During Form Submission
Mark the protected Controller action with the
CaptchaValidation attribute to include Captcha validation in
ModelState.IsValid checks:
Imports System.Web.Mvc
[…]
<HttpPost()> _
<CaptchaValidation("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA Code!")> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
If ModelState.IsValid Then
' TODO: Captcha validation failed, show error message
Else
' TODO: Captcha validation passed, proceed with protected action
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
Imports System.Web.Mvc
[…]
<HttpPost()> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
' init mvcCaptcha instance with captchaId
Dim mvcCaptcha = New MvcCaptcha("ExampleCaptcha")
' get user input value
Dim userInput As String = HttpContext.Request.Form("CaptchaCode")
' get validatingInstanceId from HttpContext.Request.Form
Dim validatingInstanceId As String = HttpContext.Request.Form(mvcCaptcha.ValidatingInstanceKey)
' or get validatingInstanceId from above mvcCaptcha instance
' Dim validatingInstanceId As String = mvcCaptcha.WebCaptcha.ValidatingInstanceId
' call the built-in Validate method from above MvcCaptcha instance.
If (mvcCaptcha.Validate(userInput, validatingInstanceId)) Then
' or you can use static Validate method of MvcCaptcha class (i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
mvcCaptcha.ResetCaptcha("ExampleCaptcha")
Else
ModelState.AddModelError("CaptchaCode", "Incorrect!")
End If
Return View(model)
4. Configure Your ASP.NET Application
Exclude BotDetect paths from ASP.NET MVC Routing:
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"})
Update your application configuration (the
web.config file):
<system.web>
<httpHandlers>
<!-- Register the HttpHandler used for BotDetect Captcha
requests -->
<add verb="GET" path="BotDetectCaptcha.ashx"
type="BotDetect.Web.CaptchaHandler, BotDetect"/>
</httpHandlers>
<!-- make sure Session State is enabled -->
<pages enableSessionState="true">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<!-- add BotDetect namespaces for coding convenience -->
<add namespace="BotDetect"/>
<add namespace="BotDetect.Web"/>
<add namespace="BotDetect.Web.UI"/>
<add namespace="BotDetect.Web.Mvc"/>
</namespaces>
</pages>
<!-- Register a custom SessionIDManager for BotDetect Captcha
requests -->
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20"
sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
</system.web>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 1 CAPTCHA / C#
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, create a
MvcCaptcha object and pass it to the Captcha
HtmlHelper:
<%@ Import Namespace="BotDetect.Web.Mvc" %>
[…]
<link href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>"
rel="stylesheet" type="text/css" />
</head>
[…]
<% MvcCaptcha exampleCaptcha = new MvcCaptcha("ExampleCaptcha");
exampleCaptcha.UserInputID = "CaptchaCode"; %>
<%: Html.Captcha(exampleCaptcha) %>
@Html.TextBox("CaptchaCode")
3. 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;
[…]
[AcceptVerbs(HttpVerbs.Post)]
[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");
}
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
using BotDetect.Web.Mvc;
[…]
[AcceptVerbs(HttpVerbs.Post)]
[AllowAnonymous]
public ActionResult ExampleAction(ExampleModel model)
{
// init mvcCaptcha instance with captchaId
MvcCaptcha mvcCaptcha = new MvcCaptcha("ExampleCaptcha");
// get user input value
string userInput = HttpContext.Request.Form["CaptchaCode"];
// get validatingInstanceId from HttpContext.Request.Form
string validatingInstanceId = HttpContext.Request.Form[mvcCaptcha.ValidatingInstanceKey];
// or get validatingInstanceId from above mvcCaptcha instance
//string validatingInstanceId = mvcCaptcha.WebCaptcha.ValidatingInstanceId;
// call the built-in Validate method from above MvcCaptcha instance.
if (mvcCaptcha.Validate(userInput, validatingInstanceId))
{
// or you can use static Validate method of MvcCaptcha class
(i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
}
else
{
ModelState.AddModelError("CaptchaCode", "Incorrect!");
}
return View(model);
}
4. Configure Your ASP.NET Application
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" });
Update your application configuration (the
web.config file):
<system.web>
<httpHandlers>
<!-- Register the HttpHandler used for BotDetect Captcha
requests -->
<add verb="GET" path="BotDetectCaptcha.ashx"
type="BotDetect.Web.CaptchaHandler, BotDetect"/>
</httpHandlers>
<!-- make sure Session State is enabled -->
<pages enableSessionState="true">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<!-- add BotDetect namespaces for coding convenience -->
<add namespace="BotDetect"/>
<add namespace="BotDetect.Web"/>
<add namespace="BotDetect.Web.UI"/>
<add namespace="BotDetect.Web.Mvc"/>
</namespaces>
</pages>
<!-- Register a custom SessionIDManager for BotDetect Captcha
requests -->
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20"
sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
</system.web>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
ASP.NET MVC 1 CAPTCHA / VB.NET
1. Add a Reference to BotDetect
Both the BotDetect.dll and BotDetect.Web.Mvc.dll assemblies should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
In View code: import the BotDetect namespace, include BotDetect styles in page
<head>, create a
MvcCaptcha object and pass it to the Captcha
HtmlHelper:
<%@ Import Namespace="BotDetect.Web.Mvc" %>
[…]
<link href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>"
rel="stylesheet" type="text/css" />
</head>
[…]
<% Dim exampleCaptcha As MvcCaptcha = New MvcCaptcha("ExampleCaptcha")
exampleCaptcha.UserInputID = "CaptchaCode"%>
<%: Html.Captcha(exampleCaptcha) %>
<%: Html.TextBox("CaptchaCode") %>
3. Check User Input During Form Submission
Mark the protected Controller action with the
CaptchaValidation attribute to include Captcha validation in
ModelState.IsValid checks:
Imports System.Web.Mvc
[…]
<AcceptVerbs(HttpVerbs.Post)> _
<CaptchaValidation("CaptchaCode", "ExampleCaptcha", "Incorrect CAPTCHA Code!")> _
Public Function Index(ByVal model As ExampleModel) As ActionResult
If ModelState.IsValid Then
' TODO: Captcha validation failed, show error message
Else
' TODO: Captcha validation passed, proceed with protected action
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
Use the built-in Validate method of a MvcCaptcha instance.
In cases when a CaptchaControl instance is not available, use static Validate method of MvcCaptcha class.
Imports System.Web.Mvc
[…]
<HttpPost()> _<AcceptVerbs(HttpVerbs.Post)> _ ' init mvcCaptcha instance with captchaId
Dim mvcCaptcha = New MvcCaptcha("ExampleCaptcha")
' get user input value
Dim userInput As String = HttpContext.Request.Form("CaptchaCode")
' get validatingInstanceId from HttpContext.Request.Form
Dim validatingInstanceId As String = HttpContext.Request.Form(mvcCaptcha.ValidatingInstanceKey)
' or get validatingInstanceId from above mvcCaptcha instance
' Dim validatingInstanceId As String = mvcCaptcha.WebCaptcha.ValidatingInstanceId
' call the built-in Validate method from above MvcCaptcha instance.
If (mvcCaptcha.Validate(userInput, validatingInstanceId)) Then
' or you can use static Validate method of MvcCaptcha class (i.e. MvcCaptcha.Validate("ExampleCaptcha", userInput, validatingInstanceId); )
mvcCaptcha.ResetCaptcha("ExampleCaptcha")
Else
ModelState.AddModelError("CaptchaCode", "Incorrect!")
End If
Return View(model)
4. Configure Your ASP.NET Application
Exclude BotDetect paths from ASP.NET MVC Routing:
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"})
Update your application configuration (the
web.config file):
<system.web>
<httpHandlers>
<!-- Register the HttpHandler used for BotDetect Captcha
requests -->
<add verb="GET" path="BotDetectCaptcha.ashx"
type="BotDetect.Web.CaptchaHandler, BotDetect"/>
</httpHandlers>
<!-- make sure Session State is enabled -->
<pages enableSessionState="true">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<!-- add BotDetect namespaces for coding convenience -->
<add namespace="BotDetect"/>
<add namespace="BotDetect.Web"/>
<add namespace="BotDetect.Web.UI"/>
<add namespace="BotDetect.Web.Mvc"/>
</namespaces>
</pages>
<!-- Register a custom SessionIDManager for BotDetect Captcha
requests -->
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20"
sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
</system.web>
<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>
In-Depth ASP.NET MVC CAPTCHA Instructions and Explanations
Detailed ASP.NET MVC Captcha instructions and explanations can be found in the ASP.NET MVC Captcha integration how to guide.
[back to top]
1. Add a Reference to BotDetect
The BotDetect.dll assembly should be referenced. They are included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
Import the BotDetect namespace, include BotDetect styles in page
<head>, create a
Captcha object and pass it to the Captcha
HtmlHelper:
@using BotDetect.Web;
[…]
<link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"
rel="stylesheet" type="text/css" />
</head>
[…]
@{
Captcha exampleCaptcha = new Captcha("ExampleCaptcha");
exampleCaptcha.UserInputID = "CaptchaCode";
}
@Html.Raw(exampleCaptcha.Html)
@Html.TextBox("CaptchaCode")
3. Check User Input During Form Submission
When the form is submitted, the Captcha validation result must be checked:
@if ((Request.HttpMethod == "POST"))
{
bool isHuman = exampleCaptcha.Validate();
if (isHuman)
{
<span class="correct">Correct!</span>
}
else
{
<span class="incorrect">Incorrect!</span>
}
}
4. Configure Your ASP.NET Application
Update your application configuration (the
web.config file):
<system.web>
<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>
<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>
1. Add a Reference to BotDetect
The BotDetect.dll assemby (and a example project made by following these instructions, named "Basic CAPTCHA example") is included in the BotDetect installation.
2. Show a Captcha Challenge on the Form
On the ASP.NET form you want to protect against bots, add:
<%@ Register Assembly="BotDetect" Namespace="BotDetect.Web.UI"
TagPrefix="BotDetect" %>
[…]
<BotDetect:WebFormsCaptcha runat="server" ID="ExampleCaptcha"
UserInputControlID="CaptchaCodeTextBox" />
<asp:TextBox ID="CaptchaCodeTextBox" runat="server" />
3. Check User Input During Form Submission
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
MvcCaptcha.ResetCaptcha("ExampleCaptcha");
}
}
4. Configure Your ASP.NET Application
Update your application configuration (the
web.config file):
<system.web>
<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>
<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 CAPTCHA Options
To find more about configuring BotDetect and integrating it in various usage scenarios, please check the getting started with BotDetect Captcha page.