As easy as it is to develop a web form that accepts user input, it is just as easy to develop an automated application that can fill the web form with data. In an attempt defend against these applications; web authors often implement a challenge-response mechanism to verify that the web form has been completed by a “human”. This challenge-response mechanism is commonly referred to as CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart). The key to a CAPTCHA mechanism is to make it easy for humans and difficult for “computers” to solve. One popular method is to generate random text for a human to enter as part of the data entry process.

There are many commercial and free CAPTCHA plugins available for use, but you can easily create a CAPTCHA as part of your web application. To incorporate your own CAPTCHA mechanism into your web form:
- Add a method to generate the “random text”
public void SetCAPTCHAText()
{
// generate a random number
Random ran = new Random();
int no = ran.Next(11111, 99999);
// store the random number in a session variable
Session["Captcha"] = no.ToString();
}
Add a method to validate the “random text” with user input
protected void CAPTCHAValidate(object source, ServerValidateEventArgs args)
{
if (Session["Captcha"] != null)
{
if (txtVerify.Text.ToUpper() != Session["Captcha"].ToString().ToUpper())
{
SetCAPTCHAText();
args.IsValid = false;
return;
}
}
else
{
SetCAPTCHAText();
args.IsValid = false;
return;
}
}
- Add a new Generic Handler to your Web Site to draw the image containing the “random text”
public void ProcessRequest(HttpContext context)
{
//factor for scaling
int factor = 25;
// set the size of the image
int imagewidth = 150;
int imageheight = 30;
// setup the image
Bitmap bmpOut = new Bitmap(imagewidth, imageheight);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, imagewidth, imageheight);
// draw the verification code on the image
Color c = new Color();
c = Color.Black;
Font f = new Font("Verdana", 14);
SolidBrush b = new SolidBrush(c);
if (!String.IsNullOrEmpty(System.Web.HttpContext.Current.Session["Captcha"].ToString()))
{
g.DrawString(System.Web.HttpContext.Current.Session["Captcha"].ToString(), f, b, 5, 5);
}
// draw some random data to image to distort OCR
Random rnd = new Random();
int m = imagewidth / factor;
for (int i = 0; i <= Convert.ToInt32(Math.Truncate(bmpOut.Width * bmpOut.Height / (double)factor)) - 1; i++)
{
int x = rnd.Next(bmpOut.Width);
int y = rnd.Next(bmpOut.Height);
int w = rnd.Next(m);
int h = rnd.Next(m);
g.FillEllipse(Brushes.Gray, x, y, w, h);
// you could get creative with other "noise"
//Point[] points = { new Point(100, 25), new Point(90, 20), new Point(110, 15), new Point(85, 15) };
//g.FillClosedCurve(Brushes.Red, points);
}
// write the image to the stream for display on the webpage
MemoryStream ms = new MemoryStream();
bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] bmpBytes = ms.GetBuffer();
bmpOut.Dispose();
g.Dispose();
ms.Close();
context.Response.BinaryWrite(bmpBytes);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
- Add an image to the web form to display the CAPTCHA text – the image is drawn by the Handler
- Add a text box for the user input
- Validate the user input when the user submits the form
<div>
<asp:Image ID="imCaptcha" ImageUrl="~/Captcha.ashx" runat="server" /><br />
<asp:TextBox ID="txtVerify" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="txtVerify"
ErrorMessage="Invalid verification code entered." OnServerValidate="CAPTCHAValidate"
SetFocusOnError="True" ValidateEmptyText="True"
ToolTip="Invalid verification code entered.">*</asp:CustomValidator><br />
<asp:Label ID="Label4" runat="server" Text="Enter the number displayed above."></asp:Label><br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"
Text="Submit" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
</div>
The sample application referenced in this post can be downloaded >>>here<<<.