In this article, I will explain you about adding Captcha image in your ASP.NET web-forms using C# and validate that captcha.

CAPTCHA is used to identify end user as a human. Many websites are using captcha technique to identify humans. Let's see how to implement captcha in Asp.net and how Captcha works with session and text string challenge.

MS CAPTCHA is a free component for ASP.NET which implements “Completely Automated Public Turing test to tell Computers and Humans Apart” – an image which “only people” could read. In case of Mondor’s CAPTCHA, it also contains the unique feature called “Arithmetic”, which displays simple formula, so even if the bot will be able to read “2 + 2”, it will type “2+2” as an answer, while there should be 4.

So let's begin with implementing MSCaptcha in our project, first of all, download the MSCaptcha dll from the below Link: download dll for Captcha

After that add the dll reference by right click on Project Name > Add > Reference > Browse > OK.

OR You can simply copy and Paste the dll in the Project Bin Folder.

After you have added .dll files successfully in the project, you need to create .aspx page with reference of the MSCaptcha at the top of the page using code as below

<%@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="ks" %>

Now, Write the below code to add a Captcha control, a Textbox, a Button to verify the Captcha and a Label to showing the error to a Web Page as shown in below Code:

<form id="form1" runat="server">
         <div>
        <ks:CaptchaControl ID="Captcha1" runat="server" CaptchaBackgroundNoise="Low" CaptchaLength="5"
            CaptchaHeight="60" CaptchaWidth="200" CaptchaMinTimeout="5" CaptchaMaxTimeout="240"
            FontColor="#0066FF" NoiseColor="#B1B1B1" CaptchaChars="ABCDEFGHJKLMNPQRSTUVWXYZ23456789" />
            <asp:Button ID="Refresh" runat="server" Text="Refresh" OnClick="RefreshImage" />
    </div>
        <div><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></div>
        <div><asp:Button ID="verify_btn" runat="server" Text="Verify" OnClick="verify_btn_Click" /></div>
        <div><b><asp:Label ID="Label1" runat="server"></asp:Label></b>
            </div>

   
    </form>

So your complete Default.aspx page will be as below

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CaptchaSample.Default" %>

<%@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="ks" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            height: 26px;
        }
        .style2
        {
            height: 17px;
        }
    </style>
</head>
<body style="font-family:Calibri">
    <form id="form1" runat="server">
         <div>
        <ks:CaptchaControl ID="Captcha1" runat="server" CaptchaBackgroundNoise="Low" CaptchaLength="5"
            CaptchaHeight="60" CaptchaWidth="200" CaptchaMinTimeout="5" CaptchaMaxTimeout="240"
            FontColor="#0066FF" NoiseColor="#B1B1B1" CaptchaChars="ABCDEFGHJKLMNPQRSTUVWXYZ23456789" />
            <asp:Button ID="Refresh" runat="server" Text="Refresh" OnClick="RefreshImage" />
    </div>
        <div><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></div>
        <div><asp:Button ID="verify_btn" runat="server" Text="Verify" OnClick="verify_btn_Click" /></div>
        <div><b><asp:Label ID="Label1" runat="server"></asp:Label></b>
            </div>

   
    </form>
</body>
</html>

In your Default.cs, write the C# code to validate captcha and Refresh the captcha image.

protected void verify_btn_Click(object sender, EventArgs e)
        {
            //Get textbox value and validate text
            Captcha1.ValidateCaptcha(TextBox1.Text.Trim());

            //if valid code is entered
            if (Captcha1.UserValidated)
            {
                Label1.ForeColor = System.Drawing.Color.Green;
                Label1.Text = "Good you are Human";
            }
            else
            {
                Label1.ForeColor = System.Drawing.Color.Red;
                Label1.Text = "Sorry! InValid Captcha";
            }
        }

        protected void RefreshImage(object sender, EventArgs e)
        {
            //Call UserValidated function to refresh, as validation will be false image get's refreshed
            var Refesh=Captcha1.UserValidated;
           
        }

One more last step is to add handlers in your Web.Config files to make captcha working.

You will need to add the following handler to <httpHandlers> in <system.web> section of your Web.Config.
<add verb="GET" path="CaptchaImage.axd" type="MSCaptcha.CaptchaImageHandler, MSCaptcha"/>

After adding the above line your web config should look like this

<system.web>
 <httpHandlers>
    <add verb="GET" path="CaptchaImage.axd" type="MSCaptcha.CaptchaImageHandler, MSCaptcha"/>
 </httpHandlers>
</system.web>

In your <system.web.server> section of Web.Config file, add the below code

 <handlers>
      <add name="MSCaptcha.captchaImageHandler" verb="GET" path="CaptchaImage.axd" type="MSCaptcha.captchaImageHandler, MSCaptcha" resourceType="Unspecified" />
    </handlers>

It would look like

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="MSCaptcha.captchaImageHandler" verb="GET" path="CaptchaImage.axd" type="MSCaptcha.captchaImageHandler, MSCaptcha" resourceType="Unspecified" />
    </handlers>
  </system.webServer>

So your Complete Web.Config file should be similar to this

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <!-- The following section will only work in ASP.NET Development Server and IIS6  -->
    <httpHandlers>
      <add verb="GET" path="CaptchaImage.axd" type="MSCaptcha.captchaImageHandler, MSCaptcha" />
    </httpHandlers>
  </system.web>
  <!-- The following section is only needed for IIS7 and up -->
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="MSCaptcha.captchaImageHandler" verb="GET" path="CaptchaImage.axd" type="MSCaptcha.captchaImageHandler, MSCaptcha" resourceType="Unspecified" />
    </handlers>
  </system.webServer>
</configuration>

web-config-captcha-in-asp-net-min.png

We are done, build and run your project in the browser and you will see the output as below

captcha-in-aspnet-c-sharp-min.png

Here is the working Gif image of the captcha

captcha-in-asp-net-min.gif

You can download the project from here if needed.