CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

A Simple CAPTCHA Image Verification in C# and ASP.Net
Submitted By Satheesh Babu B
On 2/16/2009 7:48:05 AM
Tags: asp.net,C#,CodeDigest  

A Simple CAPTCHA Image Verification in C# and ASP.Net

 

Websites(hosted in internet domains)  that offer users to post contents will have a greater threat from spammers and automated programs that can submit spam contents. So, it is vital to have a mechanism to verify the users if they are really humans who are posting the contents.

 

The following little article will help fighting this threat using a simple CAPTCHA image verification developed using HttpHandler and Session variable.

 

To develop this,

 

Include a Generic HttpHandler that can render the content of a Session variable as an image. Refer the below code snippet that generates an image from Session variable.

 

Captcha.ashx

<%@ WebHandler Language="C#" Class="Captcha" %>

using System;

using System.Web;

using System.Drawing;

using System.IO;

using System.Web.SessionState;

 

public class Captcha : IHttpHandler, IReadOnlySessionState

{

   

    public void ProcessRequest (HttpContext context) {

        Bitmap bmpOut = new Bitmap(200, 50);

        Graphics g = Graphics.FromImage(bmpOut);

        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

        g.FillRectangle(Brushes.Black, 0, 0, 200, 50);

        g.DrawString(context.Session["Captcha"].ToString(), new Font("Verdana", 18), new SolidBrush(Color.White), 0, 0);

        MemoryStream ms = new MemoryStream();

        bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

        byte[] bmpBytes = ms.GetBuffer();

        bmpOut.Dispose();

        ms.Close();

        context.Response.BinaryWrite(bmpBytes);

        context.Response.End();

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

 

}

Read my previous code snippet that explains how to generate image from a string using C# and ASP.NET. The above HttpHandler uses the same code discussed in the code snippet. Rendering the contents as an image will prevent the automatic software programs from reading its contents.

 

How to use it in our ASPX page?

 

It is very simple. Include an ASPX page (Default.aspx in our example). Drag an Image control and textbox control to enter the displayed code. With the help of custom validator control, we can validate the user input with Session variable content. Refer the below code that has the ASPX markup.

 

Default.aspx

<div>

      <asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="txtVerify"

            ErrorMessage="You have Entered a Wrong Verification Code!Please Re-enter!!!" OnServerValidate="CAPTCHAValidate"></asp:CustomValidator>      

     <asp:Image ID="imCaptcha" ImageUrl="~/CAPTCHA/Captcha.ashx" runat="server" />

        <asp:TextBox ID="txtVerify" runat="server"></asp:TextBox>

        <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" /></div>

 

Default.aspx.cs

public partial class CAPTCHA_Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        //ImageVerification

        if (!IsPostBack)

        {

            SetVerificationText();          

        }

    }

    public void SetVerificationText()

    {

        Random ran = new Random();

        int no = ran.Next();

        Session["Captcha"] = no.ToString();

    }

    protected void CAPTCHAValidate(object source, ServerValidateEventArgs args)

    {

        if (Session["Captcha"] != null)

        {

            if (txtVerify.Text != Session["Captcha"].ToString())

            {               

                SetVerificationText();

                args.IsValid = false;

                return;

            }

        }

        else

        {          

            SetVerificationText();

            args.IsValid = false;

            return;

        }

     

    }

    protected void btnSave_Click(object sender, EventArgs e)

    {

        if (!Page.IsValid)

        {

            return;

        }

            //Save the content

        Response.Write("You are not a SPAMMER!!!");

        SetVerificationText();

    }

}

 

The above code initializes the Session variable (Session["Captcha"]) with a random number which is then rendered as a image by the HttpHandler on execution of the page.

 

The page will be returned to the user with an error message "You have Entered a Wrong Verification Code!Please Re-enter!!!", if the user types a wrong code in the verification textbox.

 

Happy Coding!!!

 

 

 

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..