| |
|
Easy to use, ASP.NET Captcha Control, written in C#
By Vishal Khanna, 8th Aug, 09
Checkout an easy to use, simple ASP.NET CAPTCHA Control, free source code, you will be able to set up this captcha in 5 minutes, and further enhance the security of your website, protect spam. Code written in C#.
The code below taps the powers of C#.
Step 1: Create a web page by the name "Captcha.aspx". In the code behind of this page, paste the 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)
{
this.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.BlueViolet, 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();
}
}
The trick in the code above is the usage of the Response.ContentType property, and setting it to "Image/jpeg".
Step 2:
Create any page, say a default.aspx, or a login.aspx. Copy the following in the aspx page:
< asp:image ID="Image1" runat=server ImageUrl="~/Captcha.aspx"/>
<asp:TextBox ID="txtanswer" runat="server" Width="40px" Height="26"></asp:TextBox>
<asp:Button id="btngo" runat="server" onclick="btngo_Click" Text="Check"/>
<br />
<asp:Label ID="lbresult" runat="server" Text=""></asp:Label>
Step 3: Copy the code below in the code behind of the form you created:
protected void btngo_Click(object sender, EventArgs e)
{
if (Session["answer"].ToString() == txtanswer.Text)
{
lbresult.Text = "Pass";
}
else
{
lbresult.Text = "Fail";
}
}
There you are, ready to go with a feather on top of your website's security.
Happy Programming.
Cheers!
| |