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.

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.

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.

Captcha for Verification in ASP.NET
Tagged on: