说明:刚一朋友问我ASP.NET中验证码的编写,模糊中似乎记得以前刚学时写过一个,于是找了下,果然在CSDN上写过一篇,现将其转过来.
第一步:新建login.aspx页面,在html[源文件]中写入以下代码:
说明:刚一朋友问我ASP.NET中验证码的编写,模糊中似乎记得以前刚学时写过一个,于是找了下,果然在CSDN上写过一篇,现将其转过来.
第一步:新建login.aspx页面,在html[源文件]中写入以下代码:
Code
<input class=colorccc id=reloadvcade onclick="document.getElementById('vcodeimg').src='VerifyImage.aspx?time=' + Math.random()" type=button value=刷新验证码 name=reloadvcade style="z-index: 103; left: 369px; position: absolute; top: 253px" >
<img src="VerifyImage.aspx" id="vcodeimg" style="z-index: 104; left: 279px; position: absolute; top: 254px">
<asp:Button ID="Btn" runat="server" OnClick="Btn_Click" Style="z-index: 100; left: 305px;
position: absolute; top: 309px" Text="登录" />
<asp:TextBox ID="TextBox1" runat="server" Style="z-index: 101; left: 256px; position: absolute;
top: 197px"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Style="z-index: 105; left: 326px; position: absolute;
top: 360px" Text="Label"></asp:Label>
第二步:在login.aspx.cs页中写入以下代码:
<input class=colorccc id=reloadvcade onclick="document.getElementById('vcodeimg').src='VerifyImage.aspx?time=' + Math.random()" type=button value=刷新验证码 name=reloadvcade style="z-index: 103; left: 369px; position: absolute; top: 253px" >
<img src="VerifyImage.aspx" id="vcodeimg" style="z-index: 104; left: 279px; position: absolute; top: 254px">
<asp:Button ID="Btn" runat="server" OnClick="Btn_Click" Style="z-index: 100; left: 305px;
position: absolute; top: 309px" Text="登录" />
<asp:TextBox ID="TextBox1" runat="server" Style="z-index: 101; left: 256px; position: absolute;
top: 197px"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Style="z-index: 105; left: 326px; position: absolute;
top: 360px" Text="Label"></asp:Label>
Code
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Btn_Click(object sender, EventArgs e)
{
if (String.Compare(Request.Cookies["checkCode"].Value, TextBox1.Text, true) != 0)
{
Label1.Text = "验证码错误!";
Label1.Visible = true;
return;
}
else
{
Response.Redirect("http://www.baidu.com");
//将这改为其它代码
}
}
第三步: 新建页面VerifyImage.aspx页面,在html[源文件]页面中只写入以下代码:protected void Page_Load(object sender, EventArgs e)
{
}
protected void Btn_Click(object sender, EventArgs e)
{
if (String.Compare(Request.Cookies["checkCode"].Value, TextBox1.Text, true) != 0)
{
Label1.Text = "验证码错误!";
Label1.Visible = true;
return;
}
else
{
Response.Redirect("http://www.baidu.com");
//将这改为其它代码
}
}
<%@ Page Inherits="LongJunVerifyImage.VerifyImagePage" %>
第四步:新建VerifyImage.cs类,其代码为:
Code
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Security.Cryptography;
namespace LongJunVerifyImage
{
/// <summary>
/// 验证码图片类
/// </summary>
public class VerifyImage
{
/// <summary>
/// 要显示的文字
/// </summary>
public string Text
{
get { return this.text; }
}
/// <summary>
/// 图片
/// </summary>
public Bitmap Image
{
get { return this.image; }
}
/// <summary>
/// 宽度
/// </summary>
public int Width
{
get { return this.width; }
}
/// <summary>
/// 高度
/// </summary>
public int Height
{
get { return this.height; }
}
private string text;
private int width;
private int height;
private Bitmap image;
private static byte[] randb = new byte[4];
private static RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
/// <summary>
/// 构造函数
/// </summary>
/// <param name="code">要显示的验证码</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
public VerifyImage(string code, int width, int height)
{
this.text = code;
this.width = width;
this.height = height;
this.GenerateImage();
}
~VerifyImage()
{
Dispose(false);
}
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
this.image.Dispose();
}
private FontFamily[] fonts = {
new FontFamily("Times New Roman"),
new FontFamily("Georgia"),
new FontFamily("Arial"),
new FontFamily("Comic Sans MS")
};
public static int Next()
{
rand.GetBytes(randb);
int value = BitConverter.ToInt32(randb, 0);
if (value < 0) value = -value;
return value;
}
public static int Next(int max)
{
rand.GetBytes(randb);
int value = BitConverter.ToInt32(randb, 0);
value = value % (max + 1);
if (value < 0) value = -value;
return value;
}
public static int Next(int min, int max)
{
int value = Next(max - min) + min;
return value;
}
/// <summary>
/// 生成验证码图片
/// </summary>
private void GenerateImage()
{
Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
Rectangle rect = new Rectangle(0, 0, this.width, this.height);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Color.White);
int emSize = Next(3) + 15;//(int)((this.width - 20) * 2 / text.Length);
FontFamily family = fonts[Next(fonts.Length - 1)];
Font font = new Font(family, emSize, FontStyle.Bold);
SizeF measured = new SizeF(0, 0);
SizeF workingSize = new SizeF(this.width, this.height);
while (emSize > 2 && (measured = g.MeasureString(text, font)).Width > workingSize.Width || measured.Height > workingSize.Height)
{
font.Dispose();
font = new Font(family, emSize -= 2);
}
SolidBrush drawBrush = new SolidBrush(Color.FromArgb(Next(100), Next(100), Next(100)));
for (int x = 0; x < 3; x++)
{
Pen linePen = new Pen(Color.FromArgb(Next(150), Next(150), Next(150)), 1);
g.DrawLine(linePen, new PointF(0.0F + Next(20), 0.0F + Next(this.height)), new PointF(0.0F + Next(this.width), 0.0F + Next(this.height)));
}
for (int x = 0; x < this.text.Length; x++)
{
drawBrush.Color = Color.FromArgb(Next(150) + 20, Next(150) + 20, Next(150) + 20);
PointF drawPoint = new PointF(0.0F + Next(4) + x * 15, 8.0F + Next(4));
g.DrawString(this.text[x].ToString(), font, drawBrush, drawPoint);
}
double distort = Next(5, 10) * (Next(10) == 1 ? 1 : -1);
using (Bitmap copy = (Bitmap)bitmap.Clone())
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int newX = (int)(x + (distort * Math.Sin(Math.PI * y / 84.0)));
int newY = (int)(y + (distort * Math.Cos(Math.PI * x / 54.0)));
if (newX < 0 || newX >= width) newX = 0;
if (newY < 0 || newY >= height) newY = 0;
bitmap.SetPixel(x, y, copy.GetPixel(newX, newY));
}
}
}
//g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1);
font.Dispose();
drawBrush.Dispose();
g.Dispose();
this.image = bitmap;
}
}
}
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Security.Cryptography;
namespace LongJunVerifyImage
{
/// <summary>
/// 验证码图片类
/// </summary>
public class VerifyImage
{
/// <summary>
/// 要显示的文字
/// </summary>
public string Text
{
get { return this.text; }
}
/// <summary>
/// 图片
/// </summary>
public Bitmap Image
{
get { return this.image; }
}
/// <summary>
/// 宽度
/// </summary>
public int Width
{
get { return this.width; }
}
/// <summary>
/// 高度
/// </summary>
public int Height
{
get { return this.height; }
}
private string text;
private int width;
private int height;
private Bitmap image;
private static byte[] randb = new byte[4];
private static RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
/// <summary>
/// 构造函数
/// </summary>
/// <param name="code">要显示的验证码</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
public VerifyImage(string code, int width, int height)
{
this.text = code;
this.width = width;
this.height = height;
this.GenerateImage();
}
~VerifyImage()
{
Dispose(false);
}
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
this.image.Dispose();
}
private FontFamily[] fonts = {
new FontFamily("Times New Roman"),
new FontFamily("Georgia"),
new FontFamily("Arial"),
new FontFamily("Comic Sans MS")
};
public static int Next()
{
rand.GetBytes(randb);
int value = BitConverter.ToInt32(randb, 0);
if (value < 0) value = -value;
return value;
}
public static int Next(int max)
{
rand.GetBytes(randb);
int value = BitConverter.ToInt32(randb, 0);
value = value % (max + 1);
if (value < 0) value = -value;
return value;
}
public static int Next(int min, int max)
{
int value = Next(max - min) + min;
return value;
}
/// <summary>
/// 生成验证码图片
/// </summary>
private void GenerateImage()
{
Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
Rectangle rect = new Rectangle(0, 0, this.width, this.height);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Color.White);
int emSize = Next(3) + 15;//(int)((this.width - 20) * 2 / text.Length);
FontFamily family = fonts[Next(fonts.Length - 1)];
Font font = new Font(family, emSize, FontStyle.Bold);
SizeF measured = new SizeF(0, 0);
SizeF workingSize = new SizeF(this.width, this.height);
while (emSize > 2 && (measured = g.MeasureString(text, font)).Width > workingSize.Width || measured.Height > workingSize.Height)
{
font.Dispose();
font = new Font(family, emSize -= 2);
}
SolidBrush drawBrush = new SolidBrush(Color.FromArgb(Next(100), Next(100), Next(100)));
for (int x = 0; x < 3; x++)
{
Pen linePen = new Pen(Color.FromArgb(Next(150), Next(150), Next(150)), 1);
g.DrawLine(linePen, new PointF(0.0F + Next(20), 0.0F + Next(this.height)), new PointF(0.0F + Next(this.width), 0.0F + Next(this.height)));
}
for (int x = 0; x < this.text.Length; x++)
{
drawBrush.Color = Color.FromArgb(Next(150) + 20, Next(150) + 20, Next(150) + 20);
PointF drawPoint = new PointF(0.0F + Next(4) + x * 15, 8.0F + Next(4));
g.DrawString(this.text[x].ToString(), font, drawBrush, drawPoint);
}
double distort = Next(5, 10) * (Next(10) == 1 ? 1 : -1);
using (Bitmap copy = (Bitmap)bitmap.Clone())
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int newX = (int)(x + (distort * Math.Sin(Math.PI * y / 84.0)));
int newY = (int)(y + (distort * Math.Cos(Math.PI * x / 54.0)));
if (newX < 0 || newX >= width) newX = 0;
if (newY < 0 || newY >= height) newY = 0;
bitmap.SetPixel(x, y, copy.GetPixel(newX, newY));
}
}
}
//g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1);
font.Dispose();
drawBrush.Dispose();
g.Dispose();
this.image = bitmap;
}
}
}
第五步:新建VerifyImagePage.cs类,其代码为:
Code
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace LongJunVerifyImage
{
/// <summary>
/// 验证码图片页面类
/// </summary>
public class VerifyImagePage : System.Web.UI.Page
{
private string CreateAuthStr(int len)
{
int number;
StringBuilder code = new StringBuilder();
string checkCode = String.Empty;
Random random = new Random();
for (int i = 0; i < len; i++)
{
number = random.Next();
if (number % 2 == 0)
{
code.Append((char)('0' + (char)(number % 10)));
}
else
{
code.Append((char)('A' + (char)(number % 26)));
}
}
checkCode = code.ToString();
Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
return checkCode.ToString();
}
private string CreateAuthStr(int len, bool OnlyNum)
{
if (!OnlyNum)
{
return CreateAuthStr(len);
}
int number;
string checkCode = String.Empty;
StringBuilder code = new StringBuilder();
Random random = new Random();
for (int i = 0; i < len; i++)
{
number = random.Next();
code.Append((char)('0' + (char)(number % 10)));
}
checkCode = code.ToString();
Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
return checkCode.ToString();
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="e"></param>
override protected void OnInit(EventArgs e)
{
//
base.OnInit(e);
VerifyImage verifyimg = new VerifyImage(CreateAuthStr(5,true), 90, 50);
Bitmap image = verifyimg.Image;
System.Web.HttpContext.Current.Response.ContentType = "image/pjpeg";
//MemoryStream ms = new MemoryStream();
image.Save(this.Response.OutputStream, ImageFormat.Jpeg);
//System.Web.HttpContext.Current.Response.OutputStream.Write(ms.ToArray(), 0, (int)ms.Length);
}
}
}
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace LongJunVerifyImage
{
/// <summary>
/// 验证码图片页面类
/// </summary>
public class VerifyImagePage : System.Web.UI.Page
{
private string CreateAuthStr(int len)
{
int number;
StringBuilder code = new StringBuilder();
string checkCode = String.Empty;
Random random = new Random();
for (int i = 0; i < len; i++)
{
number = random.Next();
if (number % 2 == 0)
{
code.Append((char)('0' + (char)(number % 10)));
}
else
{
code.Append((char)('A' + (char)(number % 26)));
}
}
checkCode = code.ToString();
Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
return checkCode.ToString();
}
private string CreateAuthStr(int len, bool OnlyNum)
{
if (!OnlyNum)
{
return CreateAuthStr(len);
}
int number;
string checkCode = String.Empty;
StringBuilder code = new StringBuilder();
Random random = new Random();
for (int i = 0; i < len; i++)
{
number = random.Next();
code.Append((char)('0' + (char)(number % 10)));
}
checkCode = code.ToString();
Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
return checkCode.ToString();
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="e"></param>
override protected void OnInit(EventArgs e)
{
//
base.OnInit(e);
VerifyImage verifyimg = new VerifyImage(CreateAuthStr(5,true), 90, 50);
Bitmap image = verifyimg.Image;
System.Web.HttpContext.Current.Response.ContentType = "image/pjpeg";
//MemoryStream ms = new MemoryStream();
image.Save(this.Response.OutputStream, ImageFormat.Jpeg);
//System.Web.HttpContext.Current.Response.OutputStream.Write(ms.ToArray(), 0, (int)ms.Length);
}
}
}
<完毕>