Tony’s Weblog

ASP.NET, MVC, AJAX, SilverLight, C#, WCF Web Service, SQL 2005 and other interesting stuff.

Implement a simple captcha in C#.NET

Posted by Tony on September 1, 2008

1. Create a page with name “Captcha.aspx”

2. Place the following html code in body part of the page

   1: IMG height="30" alt="" src=BuildCaptcha.aspx width="80">
   2: asp:TextBox runat="Server" ID="txtCaptcha">
   3: <asp:Button runat="Server" ID="btnSubmit"
   4:            OnClick="btnSubmit_Click"
   5:            Text="Submit" />
   6:
   7: 3. On “btnSubmit_Click” place the following code
   8:
   9: if (Page.IsValid && (txtCaptcha.Text.ToString() ==
  10:      Session["RandomStr"].ToString()))
  11: {
  12:   Response.Write("Code verification Successful");
  13: }
  14: else
  15: {
  16:   Response.Write( "Please enter info correctly");
  17: }

3. Include the following code in “BuildCaptcha.aspx

   1: Bitmap objBMP = new Bitmap(60, 20);
   2: Graphics objGraphics = Graphics.FromImage(objBMP);
   3: objGraphics.Clear(Color.Wheat);
   4: objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
   5:
   6:
   7: //' Configure font to use for text
   8: Font objFont = new Font("Arial", 8, FontStyle.Italic);
   9: string randomStr = "";
  10: char[] myArray = new char[5];
  11: int x;
  12:
  13: //That is to create the random # and add it to our string
  14: Random autoRand = new Random();
  15: for (x = 0; x < 5; x++)
  16: {
  17:   myArray[x] = System.Convert.ToChar(autoRand.Next(65,90));
  18:   randomStr += (myArray[x].ToString());
  19: }
  20:
  21: //This is to add the string to session, to be compared later
  22: Session.Add("RandomStr", randomStr);
  23:
  24: //' Write out the text
  25: objGraphics.DrawString(randomStr, objFont, Brushes.Red, 3, 3);
  26:
  27: //' Set the content type and return the image
  28: Response.ContentType = "image/GIF";
  29: objBMP.Save(Response.OutputStream, ImageFormat.Gif);
  30: objFont.Dispose();
  31: objGraphics.Dispose();
  32: objBMP.Dispose();

4. There you go you can test the page with captcha. Happy Programming!

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: