Thursday, January 20, 2011

Captcha Image Verification Using Generic HTTP Handler

Dear Googler,
         In this post, I explain how to Generate the Captcha image and verify that image using Generic HTTP Handler. Here these steps are given below.



Steps:
      First Add the Generic Handler file using the "Add New Item" and then Type the Below code.

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


using System;
using System.Web;
using System.Drawing;
using System.IO;
using System.Web.SessionState;

public class Handler : IHttpHandler,IReadOnlySessionState {

public void ProcessRequest (HttpContext context) {
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");

Bitmap bmpout = new Bitmap(180, 45);
Graphics g = Graphics.FromImage(bmpout);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.Black, 0, 0, 180, 45);
g.DrawString(context.Session["captcha"].ToString(), new Font("Tahoma", 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;
}
}

}

Default.aspx:

And then in the Default.aspx, you add one custom validator control,one image control,one textbox control and one button control.

<form id="form1" runat="server">
<div>
  <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate ="TextBox1" ErrorMessage="You have Entered a wrong Captcha code! Please Re-Type!!!" OnServerValidate ="ValidateCaptcha"></asp:CustomValidator><br />
<asp:Image ID="Image1" runat="server" ImageUrl ="~/Handler.ashx" /><br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click"/>
</div>
</form>

Default.aspx.cs:

public void setcaptcha()
{
Random ra = new Random();
int cap = ra.Next();
Session["captcha"] = cap.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
setcaptcha();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!IsPostBack)
{
return;
}
  Response.Write("You Enter the Correct CAPTCHA Image!!!");
setcaptcha();
}
protected void ValidateCaptcha(object source, ServerValidateEventArgs args)
{
if (Session["captcha"] != null)
{
if (this.TextBox1.Text != Session["captcha"].ToString())
{
setcaptcha();
args.IsValid = false;
return;
}
}
else
{
setcaptcha();
args.IsValid = false;
return;
}
}

No comments:

Post a Comment