Implement a simple captcha in C# .NET

  • Create a page with name “Captcha.aspx
  • Place the following html code in body part of the page

IMG height="30" alt="" src=BuildCaptcha.aspx width="80">
asp:TextBox runat="Server" ID="txtCaptcha">
    <asp:Button runat="Server" ID="btnSubmit"
       Text="Submit" />
     On “btnSubmit_Click” place the following code
         if (Page.IsValid && (txtCaptcha.Text.ToString() ==
             Response.Write("Code verification Successful");
  Response.Write( "Please enter info correctly");

  • Include the following code in “BuildCaptcha.aspx"

Bitmap objBMP = new Bitmap(60, 20);
Graphics objGraphics = Graphics.FromImage(objBMP);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
  //' Configure font to use for text
      Font objFont = new Font("Arial", 8, FontStyle.Italic);
      string randomStr = "";
      char[] myArray = new char[5];
      int x;
   //That is to create the random # and add it to our string
     Random autoRand = new Random();
     for (x = 0; x < 5; x++)
  myArray[x] = System.Convert.ToChar(autoRand.Next(65,90));
  randomStr += (myArray[x].ToString());
     //This is to add the string to session, to be compared later
       Session.Add("RandomStr", randomStr);
    //' Write out the text
       objGraphics.DrawString(randomStr, objFont, Brushes.Red, 3, 3);
    //' Set the content type and return the image
  Response.ContentType = "image/GIF";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);

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