1.新增VerificationCode.ashx页面
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.SessionState;
using System.Configuration;
using System.Drawing.Drawing2D;
public class VerificationCode : IHttpHandler,IRequiresSessionState
{
public void ProcessRequest (HttpContext context) {
//定義隨機數
//string sString = ConfigurationManager.AppSettings["CheckNumber"];
string sString = "abcABC01";//根据需要自己定义内容
Random Rnd = new Random((int)DateTime.Now.Ticks);//強制轉換為整型
string scode = null;
for (int i = 0; i < 4; i++)
{
//將隨機得到的字符進行構造字符串
string temp = sString.Substring(Rnd.Next(0, sString.Length), 1);
scode += temp;
}
//創建位圖對象並初始化寬度和高度
Bitmap Bmp = new Bitmap((int)Math.Ceiling((scode.Length * 18.5)), 30);
//創建畫布
Graphics Grc = Graphics.FromImage(Bmp);//將位圖裝載畫布裡面
//將畫布背景色改為白色
Grc.Clear(Color.White);
//定義畫筆對象
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, Bmp.Width, Bmp.Height), Color.Black, Color.Black, 1.2f, true);
//隨機輸出噪點
Random rand = new Random();
for (int i = 0; i <500; i++)
{
int x = rand.Next(Bmp.Width);
int y = rand.Next(Bmp.Height);
//Grc.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
Bmp.SetPixel(x, y, Color.FromArgb(rand.Next()));
}
//干擾線條數
for (int i = 0; i < 5; i++)
{
int x1 = rand.Next(Bmp.Width);
int x2 = rand.Next(Bmp.Width);
int y1 = rand.Next(Bmp.Height);
int y2 = rand.Next(Bmp.Height);
Grc.DrawLine(new Pen(Color.Black, 1), x1, y1, x2, y2);//根據坐標劃線
}
Font ft = new Font("Arial", 16, ((FontStyle.Bold | FontStyle.Italic)));
Grc.DrawString(scode, ft, brush, 2, 2);
context.Response.ContentType = "image/jpg";
Bmp.Save(context.Response.OutputStream, ImageFormat.Gif);
//向外傳scode值已驗證
context.Session["CheckNumber"] = scode;
}
public bool IsReusable {
get {
return false;
}
}
}
2.aspx前台代码
<label for="txtCheckNumber" class="text-left"><i class="icon-tags"></i>驗證碼</label>
<asp:TextBox ID="txtCheckNumber" runat="server" TextMode="SingleLine" placeholder="Type Verification code..." CssClass="input-block-level" ToolTip="Please Type Verification code..."></asp:TextBox>
<div class="text-center" style="color: gray">
看不清?點擊圖片換一張<asp:ImageButton ID="imageBtn" runat="server" src="VerificationCode.ashx" />
</div>
3.后台方法
//點擊圖片更換驗證碼
protected void imageBtn_Click(object sender, ImageClickEventArgs e)
{
imageBtn.ImageUrl = "VerificationCode.ashx?id=" + new Random(100).ToString();
}
4.根据条件需要放入自己的代码中进行判断
//不區分大小寫驗證
if (String.Compare(txtCheckNumber.Text.Trim(), Session["CheckNumber"].ToString(), true) != 0)
{
AlertMessage("驗證碼錯誤");
txtCheckNumber.Focus();
return;
}