验证码
新建vcode.aspx页面
vcode.aspx.cs代码为
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public partial class admin_vcode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.ValidateCode(RndNum(4));
}
/// <summary>
/// 该方法是将生成的随机数写入图像文件
/// </summary>
/// <param name="VNum">VNum是一个随机数</param>
private void ValidateCode(string VNum)
{
Bitmap Img = null;
Graphics g = null;
MemoryStream ms = null;
int gheight = VNum.Length * 12;//定义图像的大小
Img = new Bitmap(gheight, 25);//生成图像的实例
g = Graphics.FromImage(Img);//从Img对象生成新的Graphics对象
Font f = new Font("Arial Black", 10);//生成Font类的实例
SolidBrush s = new SolidBrush(Color.White);//生成笔刷类的实例
g.DrawString(VNum, f, s, 3, 3);//将VNum写入图片中
ms = new MemoryStream();//生成内存流对象
Img.Save(ms, ImageFormat.Jpeg);//将此图像以Png图像文件的格式保存到流中
Response.ClearContent();//更改http ContentType
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());//将整个二进制流的内容写入字节数组
//回收资源
g.Dispose();
Img.Dispose();
Response.End();
}
/// <summary>
/// 该方法用于生成指定位数的随机数
/// </summary>
/// <param name="VcodeNum">参数是随机数的位数</param>
/// <returns>返回一个随机数字符串</returns>
private string RndNum(int VcodeNum)
{
string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p" +
",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q" +
",R,S,T,U,V,W,X,Y,Z";
string[] VcArray = Vchar.Split(new Char[] { ',' });//拆分成数组
string VNum = "";
int temp = -1;//记录上次随机数值,尽量避避免生产几个一样的随机数
Random rand = new Random();
//采用一个简单的算法以保证生成随机数的不同
for (int i = 1; i < VcodeNum + 1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
}
int t = rand.Next(61);
if (temp != -1 && temp == t)
{
return RndNum(VcodeNum);
}
temp = t;
VNum += VcArray[t];
}
Session["code"] = VNum;
return VNum;
}
}
在需要用到验证码的引用页面:<asp:Image ID="Image1" runat="server" ImageUrl="vcode.aspx" />或者
<img src="vcode.aspx" alt="看不清楚,重新一张" onclick="this.src='vcode.aspx?abc='+Math.random()" style="cursor:pointer;" />
后台用session("名称") 即session("code")去匹配TextBox的输入。