Working with Captcha in MVC

Kailash Chandra Behera | Friday, April 06, 2018

Introduction

The following blog provides code snippet about to use of captcha in MVC.

Getting Started

The following source code has been built in MVC5. It uses library from NuGet for captcha control. NuGet provides variety of library for different version of MVC.

For example, for MVC5 NuGet provides library CaptchaMvc5. As I have worked in MVC5, I have downloaded the captchamvc5 library to use in MVC5.
The CaptchaMvc library provides MathCaptcha extended function for displaying captcha in view and captcha can be validate in controller by using IsCaptchaValid extended function which takes string value for displaying validation message in view.

Steps For Use Of Captcha Control In MVC

  1. Download the appropriate captcha library from NuGet. For example, for MVC3 download captcha library CaptchaMvc3
  2. Use ‘CaptchaMvc.HtmlHelpers’ namespace in code behind(controller) and view.
  3. Use the below client code in your view for displaying captcha in view.
  4. Handle the captcha validation in controller, see the below controller code for validation details.
Go through the below code for implementing captcha in MVC.

Client-side code for Captcha.

 @using CaptchaMvc.HtmlHelpers  
 @using CaptchaMvc;  
 @using (Html.BeginForm())  
 {  
   @Html.ValidationSummary(true)  
 <fieldset>  
   @Html.MathCaptcha()  
   @ViewBag.ErrMessage  
   <p>  
     <input type="submit" value="Send" />  
   </p>    
 </fieldset>  
 }  

Server-side code for Captcha.

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using CaptchaMvc.HtmlHelpers;  
 namespace Captcha.Controllers  
 {  
   public class CaptchController : Controller  
   {  
     // GET: Captch  
     public ActionResult Index()  
     {  
       return View();  
     }  
     [HttpPost]  
     public ActionResult Index(string empty)  
     {  
       // Code for validating the CAPTCHA   
       if (this.IsCaptchaValid("Captcha is not valid")==false)  
       {  
         ViewBag.ErrMessage = "Error: captcha is not valid.";  
       }  
       return View();  
     }  
   }  
 }  

Thanks