Monday, 21 July 2014

Captcha using C# in ASP.NET

In this Article, I will explain how to incorporate Captcha Control in ASP.Net. Captcha control helps to avoid spam and generally used in Contact us or Sign Up forms.
Basically the user is shown an image with some characters and user has to fill the same character in a textbox provided, then the content of the image is matched with the textbox and if it matches it ensures that it’s a valid submission and the form gets submitted.
To start with you will need o download the Free Captcha User Control from here
Once it is done you will need to add reference of the same
Right Click your Website and Click Add Reference


Add Reference


Browse and select the DLL File


Browse and Select the DLL File


Once the reference is added you will need to add this key to the web.config
<add verb="GET" path="CaptchaImage.axd"
 type="MSCaptcha.CaptchaImageHandler, MSCaptcha" />

As shown below in the httpHandlers section


Adding key to Web.Config


Now Register the control on your page using the following
<%@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="cc1" %>

As shown below


Registering the User Control


Now add the Captcha control on the page where you intend to place it
<cc1:CaptchaControl ID="Captcha1" runat="server"
 CaptchaBackgroundNoise="Low" CaptchaLength="5"
 CaptchaHeight="60" CaptchaWidth="200"
 CaptchaLineNoise="None" CaptchaMinTimeout="5"
 CaptchaMaxTimeout="240" FontColor = "#529E00" />

As shown below


Adding the control on webpage
   
There are various parameters like which you can set
CaptchBackgroundNoise – Sets the amount of Noise you want in background noise
CaptchaLength – Length of the Captcha Text
CaptchaHeight – Height of Captcha control
CaptchaWidth – Width of Captcha control
CaptchaLineNoise – Line Noise in image
CaptchaMinTimeout – Minimum Time Captcha image is valid
CaptchaMaxTimeout – Maximum Time Captcha image is valid

To verify I have added the following code to button click event
C#
protected void btnVerify_Click(object sender, EventArgs e)
{
    Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
    if (Captcha1.UserValidated)
    {
        lblMessage.ForeColor = System.Drawing.Color.Green;
        lblMessage.Text = "Valid";
    }
    else
    {
        lblMessage.ForeColor = System.Drawing.Color.Red;
        lblMessage.Text = "InValid";
    }
}

VB.Net
Protected Sub btnVerify_Click(ByVal sender As Object,
ByVal e As System.EventArgs)
   Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim())
   If Captcha1.UserValidated Then
     lblMessage.ForeColor = System.Drawing.Color.Green
     lblMessage.Text = "Valid"
   Else
     lblMessage.ForeColor = System.Drawing.Color.Red
     lblMessage.Text = "InValid"
   End If
End Sub

Finally the Captcha control looks like below


Captcha Control