Tuesday 2 April 2013

How to implement Captcha in ASP.Net

How to implement Captcha in ASP.Net

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


This completes the article you can download the source code in VB.Net and C# here

No comments:

Post a Comment