Header Ads

Using Captcha in Asp.net and C#

What is CAPTCHA ?

A CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a challenge-response system test designed to differentiate humans from automated programs. A CAPTCHA differentiates between human and bot by setting some task that is easy for most humans to perform but is more difficult and time-consuming for current bots to complete,and further enhance the security of your website protect spam.

So that I have written code for simple captcha using Asp.net and C# 

Step 1 : Create the web page by the name is captcha.aspx, In the code behind of this page you write following code

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;

public partial class Captcha : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
returnNumer();
}

private void returnNumer()
{

Random num1 = new Random();

Random num2 = new Random();

int numQ1 = 0;

int numQ2 = 0;

string QString = null;

numQ1 = num1.Next(10, 15);

numQ2 = num1.Next(17, 31);

QString = numQ1.ToString() + " + " + numQ2.ToString() + " = ";

Session["answer"] = numQ1 + numQ2;

Bitmap bitmap = new Bitmap(85, 24);

Graphics Grfx = Graphics.FromImage(bitmap);

Font font = new Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel);

Rectangle Rect = new Rectangle(0, 0, 100, 50);

Grfx.FillRectangle(Brushes.CadetBlue, Rect);

Grfx.DrawRectangle(Pens.PeachPuff, Rect);

// Border

Grfx.DrawString(QString, font, Brushes.White, 0, 0);

Response.ContentType = "Image/jpeg";

bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

bitmap.Dispose();

Grfx.Dispose();

}
}



Step 2 : Create another web page by the name Default.aspx and write following code in this page

<asp:image id="imgCaptcha" imageurl="~/Captcha.aspx" runat="server"></asp:image> &nbsp;
<asp:textbox height="26" id="txtCaptcha" runat="server" width="46px"></asp:textbox>
<asp:button height="26" id="btnResult" onclick="btnResult_Click" runat="server" text="Go" width="46px"></asp:button><asp:label id="lblResult" runat="server"></asp:label>


Step 3 : Write the following code in code behind of Default page

protected void btnResult_Click(object sender, EventArgs e)
{
if (Session["answer"].ToString() == txtCaptcha.Text)
{
lblResult.Text = "Pass";
}
else
{
lblResult.Text = "Fail";
}
}

2 comments:


Powered by Blogger.