CAPTCHA Image and Verify User Input Using ADCaptcha

Step 1. Add ADCaptcha.dll to Project from NuGet Gallary or add it to your ASP.NET project's references.

NuGet\Install-Package ADCaptcha -Version 1.0.1

ADCaptcha

Step 2. Generating and Displaying a CAPTCHA Image (ASP.NET Web Form).

In your ASP.NET web form (e.g., Default.aspx), add an Image control to display the CAPTCHA image.

<asp:Image ID="CaptchaImage" CssClass="image" runat="server" ImageUrl="~/GetADCaptchaImage.aspx" />
<asp:TextBox ID="UserInputTextBox" MaxLength="5" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" CssClass="btn btn-info mt-2" />
<%--For Testing Purpose Only => DLL By ASHOK DUDI--%>
<asp:Label Text="" ID="lblMsg" runat="server" />

Import ADCaptcha Namespace: In the files where you want to use the ADCaptcha library, import the required namespaces.

For example, if your ADCaptcha.dll has the namespace, import it in the code files where you use the CAPTCHA functionalities (e.g., Default.aspx.cs).

using ADCaptcha; // Import the ADCaptcha namespace.

Default.aspx.cs Code

using ADCaptcha;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            GenerateAndDisplayCaptcha();
        }
    }
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        if (VerifyCaptcha())
        {
            // CAPTCHA verification successful.
            // Proceed with the form submission or any other action.
            // ...
            lblMsg.Text = "Success";        
        }
        else
        {
            lblMsg.Text = "Failed";
            GenerateAndDisplayCaptcha();
            UserInputTextBox.Focus();
            // CAPTCHA verification failed.
            // Show an error message to the user and ask them to try again.
            // ...
        }
    }

    private void GenerateAndDisplayCaptcha()
    {
        UserInputTextBox.Text = String.Empty;
        UserInputTextBox.Focus();
        // Generate the CAPTCHA text based on the selected difficulty mode (e.g., DifficultyMode.Medium).
        string captchaText = CaptchaGenerator.GenerateRandomText(5, DifficultyMode.Hard);

        // Store the CAPTCHA text in the session to validate user input against it.
        Session["CaptchaText"] = captchaText;

        // Set the CAPTCHA text as a query parameter to be passed to the handler (GetADCaptchaImage.aspx).
        string captchaImageUrl = "GetADCaptchaImage.aspx";

        // Set the "src" attribute of the <img> tag to the handler URL with the CAPTCHA text.
        CaptchaImage.Attributes["src"] = captchaImageUrl;
    }

    private bool VerifyCaptcha()
    {
        // Retrieve the stored CAPTCHA text from the session.
        string captchaText = Session["CaptchaText"] as string;
        // Retrieve the user's input from the TextBox.
        string userInput = UserInputTextBox.Text.Trim();
        // Verify the user's input against the CAPTCHA text (case-insensitive comparison by default).
        bool isCaptchaValid = CaptchaVerifier.VerifyCaptcha(captchaText, userInput, true);
        return isCaptchaValid;
    }
}

Create GetADCaptchaImage.aspx Page to create captcha image and page below code in GetADCaptcha.aspx.cs.

using ADCaptcha;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class GetADCaptchaImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["CaptchaText"] != null)
            {
                string captchaText = Session["CaptchaText"] as string;

                this.Response.Clear();
                this.Response.ContentType = "image/jpeg";
                using (Bitmap captchaImage = ByteArrayToBitmap(CaptchaGenerator.GenerateCaptchaImage(captchaText, 150, 60)))
                {
                    // Send the image to the response stream.
                    captchaImage.Save(this.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }
        catch (Exception)
        {

            throw;
        }
    }
    private static Bitmap ByteArrayToBitmap(byte[] byteArray)
    {
        if (byteArray == null || byteArray.Length == 0)
            throw new ArgumentException("The byte array is empty or null.");

        using (MemoryStream stream = new MemoryStream(byteArray))
        {
            return new Bitmap(stream);
        }
    }
}

Remember to adjust the code and styling to match your specific ASP.NET project structure and design. Additionally, ensure that you have properly set up the session state in your ASP.NET application to store and retrieve the CAPTCHA text for verification.