DEV Community

Shekhar Tarare
Shekhar Tarare

Posted on • Originally published at shekhartarare.com

Implement CAPTCHA on ASP.Net web application

In this article, we are going to discuss about the implementation of CAPTCHA in ASP.Net web application. I will be going to create a small web application where I’ll implement the CAPTCHA.

What is CAPTCHA:

CAPTCHA is like a test to identify a human. It consists of two parts: a text box and a distorted image where a randomly generated sequence of letters or numbers is shown. Users need to enter the characters visible on the image into the text box to pass the test otherwise it doesn’t allow to go further.

CAPTCHA stands for “Completely Automated Public Turing Test to Test Computers and Humans Apart”


Advantages of CAPTCHA:

  1. It helps in preventing automated submission of forms. If you implement the CAPTCHA in your registration page then you will not get the spam users.

  2. The primary motive of using the CAPTCHA is to avoid spam messages or users.


Implementation of CAPTCHA:

You can write your own code for implementing the CAPTCHA or else you can use the open-source libraries. It depends on you.

Step 1: Create a new ASP.Net MVC application

  1. I am using Visual Studio 2019 for creating the project.
  2. Open Visual Studio and create a new project. Search “asp.net web application”, you will get the list, from there select ASP.NET Web Application (.NET Framework) and click on Next.

    Create a new project

  3. Give a project name and select the .NET framework version from the dropdown and click on Create.

    configuration

  4. Select Empty, check the MVC checkbox and click on Create. It will create a project in a moment.

    Create


Step 2: Adding reference for CaptchaMVC from the NuGet Package Manager

  1. We are going to use the CaptchaMVC for the purpose of CAPTCHA generation.
  2. Right click References and click on “Manage NuGet Packages”.

    Manage NuGet packages

  3. Click on Browse and search for “captchamvc”, select the CaptchaMvc.Mvc5 from the list and click on Install.

    search for package

  4. It will give one pop-up, click on OK. It will install the CaptchaMvc in our project.

    Install package

  5. You can verify that by expanding the References.

    Verify


Step 3: Adding a Model

  1. Right click Models and click on Add → Class.

    Create Model

  2. Give any class name and click on Add.

    Give class name

  3. Add the following code in the class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CAPTCHADemo.Models
{
    public class Comments
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Comment { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Adding a Controller

  1. Right click Controllers and click on Add → Controller….

    Add controller

  2. Select the MVC 5 Controller — Empty from the list and click on Add.

    select the type

  3. It will open a pop-up, give any name there and click on Add.

    Give name

  4. Add the following code in the class.

using CAPTCHADemo.Models;
using CaptchaMvc.HtmlHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; 

namespace CAPTCHADemo.Controllers
{
    public class CaptchaController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Comments comments)
        {
            //Here the validation will happen
            if (this.IsCaptchaValid("Captcha is invalid"))
            {
                //redirect to this controller after verification
                return RedirectToAction("AfterVerifying");
            }

            ViewBag.Error = "Invalid Captcha";
            return View();
        }

        public ActionResult AfterVerifying()
        {
            return View();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Adding Views

  1. Right click Index action methods and click on Add View…

    Add view

  2. Select MVC 5 View and click on Add.

  3. Give a view name. Select Empty Template and a Model class from the dropdown and click on Add.

    select type

  4. Give a view name. Select Empty Template and a Model class from the dropdown and click on Add.

    Give name

  5. Add the following code.

    @model CAPTCHADemo.Models.Comments
    @using CaptchaMvc.HtmlHelpers
    @{
    ViewBag.Title = "Index";
    }
    @using (Html.BeginForm("Index", "Captcha", new {
    enctype = "multipart/form-data", id = "Captcha" }))
    {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Add your Comment</legend>
        <div class="form-group">
            <label>Name</label>
            <div>
                @Html.TextBoxFor(c => c.Name, new { @id = "Name", @class = "form-control", @placeholder = "Name", required = "required" })
            </div>
        </div>
        <div class="form-group">
            <label>Email</label>
            @Html.TextBoxFor(c => c.Email, new { @id = "Email", @class = "form-control", @placeholder = "Email", required = "required" })
        </div>
        <div class="form-group">
            <label>Comments</label>
            @Html.TextBoxFor(c => c.Comment, new { @id = "Comment", @class = "form-control", @placeholder = "Comment", required = "required" })
        </div>
        @Html.MathCaptcha()
        <br />
        <p class="text-danger"> <strong> @ViewBag.Error </strong>  </p>
        <p>
            <input type="submit" value="Submit Comment" />
        </p>
    </fieldset>
    }
    
  6. Right click AfterVerifying action methods and click on Add View… Select MVC 5 View and click on Add.

    Add a new view

  7. Give a view name. Select Empty Template and click on Add.

    Give name to it

  8. Add the following code.

    @{
    ViewBag.Title = "AfterVerifying";
    }
    <h2>Thanks!h2>
    

    Note: I have also installed the Bootstrap from the NuGet package manager to give the good look to the page.

  9. One last thing, make the following change on the RouteConfig file.

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                //Changed from Home to Captcha
                defaults: new { controller = "Captcha", action = "Index",            id = UrlParameter.Optional }
            );
        }
Enter fullscreen mode Exit fullscreen mode

Step 6: Test the changes

  1. It’s time to test our changes.

    Testing1

  2. It will give the error, if we don’t answer or enter the wrong answer.

    Testing2


Complete Code Here:

You can get the complete code on my GitHub account by going to this link.

Top comments (0)