Have you ever wondered how to create a Captcha for your web forms? Well, it's really simple and it won't take more than 100+ lines of code. This sample captcha that I will demonstrate will have random Font Type, Font Style, Font Color, Font Rotation, Background Style and Background Colour. Here are some samples of what this can generate:
Now without too much explanation, here it goes.
Step 1: In your web project, add a Generic Handler that's the file with the .ahsx extension. Ill just use this for this demo for simplicity and also it will compile on demand like a normal aspx file. It's up to you if you want to create a DLL which is better so you can reuse it in any projects you want. To do that, right click on the project on your Solution Explorer.
Then choose your file type, in this sample it's a Generic Handler.
Step 2: Once added you can start coding, here are the sample codes which you can freely copy.
<%@ WebHandler Language="C#" %>
There is some commented explanation along the way so you won't get lost, but you can still ask me if you really need.
Step 3: Use that Captcha. On your aspx, add the following as an image like such:
<asp:Image ID="imgCaptcha" ImageUrl="Captcha.ashx" runat="server" />
If you noticed, it's like you are using it as an image, this is because it's an image rendered by that handler which you can see on the bottom part of the Captcha code.
Step 4: Assign a text on that captcha on your code behind:
private void SetCaptchaText()
Random oRandom = new Random();
int iNumber = oRandom.Next(100000, 999999);
Session["Captcha"] = iNumber.ToString();
Note: You may notice that I am using only numbers in this regard, this would be easy so users cannot be confused with l and 1, 0 and o, and other similar looking characters.
Note: By setting the session, you are also setting the text to render on the captcha and if you look at the captcha codes, it is in this section.
string sCaptchaText = context.Session["Captcha"].ToString();
Step 5: Compare that value to what the users had keyed into your text box:
if (Session["Captcha"].ToString() != txtCaptcha.Text.Trim())
That's it. Congratulations! You have created your own captcha.