Tuesday, March 1, 2011

Captcha in asp.net

Creat the captha.cs class like.
public partial class captcha : System.Web.UI.Page{

{
protected void Page_Load(object sender, EventArgs e)try{
System.Drawing.
System.Drawing.
objGraphics.Clear(System.Drawing.
objGraphics.TextRenderingHint = System.Drawing.Text.
System.Drawing.





{

strRandom += strArray[i].ToString();
}
Session.Add(
objGraphics.DrawString(strRandom, objFont, System.Drawing.
Response.ContentType =
objBmp.Save(Response.OutputStream, System.Drawing.Imaging.
objFont.Dispose();
objGraphics.Dispose();
objBmp.Dispose();
}
Bitmap objBmp = new System.Drawing.Bitmap(156, 25);Graphics objGraphics = System.Drawing.Graphics.FromImage(objBmp);Color.Gray);TextRenderingHint.AntiAlias;Font objFont = new System.Drawing.Font("Blue", 12, System.Drawing.FontStyle.Bold);string strRandom = "";string[] strArray = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };Random autoRand = new Random();int x;for (x = 0; x < 5; x++)int i = Convert.ToInt32(autoRand.Next(0, 36));"strRandom", strRandom);Brushes.Black, 3, 3);"image/GIF";ImageFormat.Gif);catch{
}
}

{
ViewStateUserKey = Session.SessionID;
}
}

And use it to desier page like.

<

For check the capthca test using

aa = txtCaptcha.Text;

{
msg.InnerHtml =
txtCaptcha.Text =
txtCaptcha.Focus();
}

strRandom session automatically store the value of Captcha test.
if (Session["strRandom"].ToString() != aa)"Enter valid captcha string";"";
asp:Image ID="img_cap" ImageUrl="~/captcha.aspx" runat="server" />
private void Page_Init(object sender, EventArgs e)

No comments:

Post a Comment