Captcha for Verification in ASP.NET

Captcha differentiates between humans and bots accessing our website. In this post, we will create a simple Captcha using ASP.NET. The captcha has an image with text. This is similar to the captcha used in Google, Yahoo and other websites.

We have an Image control which has the captcha. There is a TextBox that prompts the user to enter the text embedded within the captcha. We perform our validation using a CustomValidator. The CustomValidator has an OnServerValidate event handler to validate the text with the captcha at the server.

<form id="form1" runat="server">
<div>
    <asp:Image ID="VerImage" runat="server" 
        ImageUrl="~/ImageViewer.ashx"/>
    <asp:TextBox ID="VerText" runat="server" />
    <asp:CustomValidator id="VerifyVal" runat="server" 
        ValidateEmptyText="true" 
	    ControlToValidate="VerText" 
        OnServerValidate="VerifyVal_ServerValidate">*
    </asp:CustomValidator>
    <asp:Button Text="Verify" runat="server" />
</div>
</form>

In the server-side, we handle the Page load event and CustomValidator ServerValidate event. In the Page load event, we create a verification text and store it in a session variable. In the ServerValidate event, we pick the verification text from the Session variable and validate the text entered by the user.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string verText = "Sample";
        Session["Verify"] = verText;
    }
}

protected void VerifyVal_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = false;
    string verText = (string)Session["Verify"];
    if (!String.IsNullOrEmpty(verText))
    {
        if (VerText.Text == verText)
        {
            args.IsValid = true;
        }
    }
}

Render the image in a handler class, ImageViewer.ashx. The ProcessRequest method gets the verification text from the session variable. Make sure that the handler class derives from IRequiresSessionState. IRequiresSessionState is a marker interface that allows the handler to access the Session object.

Create an image object from a background image file. Using the Graphics object, Draw the string. And then, stream the image into the Response object.

public class ImageViewer : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {    
        Image image = Image.FromFile(context.Server.MapPath("~/red.jpg"));
        Graphics gp = Graphics.FromImage(image);

        string text = "Default";
        if (context.Session!=null && context.Session["Verify"]!=null)
            text = (string)context.Session["Verify"];

        Font font = new Font(new FontFamily("Arial"), image.Height/3);
        Brush brush = Brushes.White;
        PointF point = new PointF(image.Width/4, image.Height/4);
        gp.DrawString(text, font, brush, point);

        image.Save(context.Response.OutputStream, 
            System.Drawing.Imaging.ImageFormat.Gif);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Related Posts

Leave a Reply

Your email address will not be published.