Implement CAPTCHA on ASP.Net web application
Tags: captcha, aspdotnet, webdev, tutorial
Published: 2023-07-15 08:42:32

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ixocztmuuj0u6yprtaju.png)


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

    ![configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lfmdehn5ocuuji6e7qnk.png)


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


    ![Create](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z938oluftsnlpbse8tj4.png)

---

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oc8pavi5o44m4r5344gs.png)


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

    ![search for package](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wtrfpfg0kyrvycqrldzp.png)


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

    ![Install package](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fip33qkqr1i6ayn79a6e.png)


5. You can verify that by expanding the References.


    ![Verify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fnbrt9dq9uohksilb1yk.png)

---

## Step 3: Adding a Model

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

    ![Create Model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d4xxu6c4rq2hyhmkdczx.png)


2. Give any class name and click on Add.

    ![Give class name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o06zbx0ua55bc2es30iw.png)


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; }
    }
}
```

---

## Step 4: Adding a Controller

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

    ![Add controller](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qsib59eepnpehpo47ts2.png)


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

    ![select the type](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/68yl4eoeoew49jco52h7.png)


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

    ![Give name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fx1g7upkvdu8tsu6kl9.png)


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();
        }
    }
}
```

---

## Step 5: Adding Views

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

    ![Add view](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mcl03874i2680tp3sk8c.png)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/en1z2d7pbuavn1w4a2cx.png)


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

    ![Give name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmbb4kz4gs4kxz5x4f1e.png)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7859v0kpe52aiqra2lgc.png)


7. Give a view name. Select Empty Template and click on Add.
    
    ![Give name to it](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aae0zru26kchpqx0zjbi.png)


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 }
            );
        }
```

---

## Step 6: Test the changes

1. It’s time to test our changes.

 

    ![Testing1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b20mijuqsiet2adthm6a.gif)


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

    ![Testing2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ssxqdyg3r9b623z5mqfx.gif)

---

## Complete Code Here:
You can get the complete code on my GitHub account by going to this [link](https://github.com/ShekharTarare/CAPTCHADemo).