asp.net(c#)生成验证码

    技术2022-05-11  59

    生成验证码,无非是把数字、字母或汉字混合在一起,生成图片,然后输出。这里用的是数字和字母。

    首先,登陆界面需要显示这个图片,那么,就有:

    <font color="#FF0000">请输入</font>            <img src="Validate.aspx" alt="" />

    这个来显示图片,下面是Validate.aspx:

    <%@ Page Language="C#" %><%@ import namespace="System"%><%@ import namespace="System.IO"%><%@ import namespace="System.Drawing"%><%@ import namespace="System.Drawing.Imaging"%><%@ import namespace="System.Drawing.Drawing2D"%>

    <script runat="server">private Bitmap validateimage;private Graphics g;public void  Page_Load(object Sender,EventArgs e){     Response.BufferOutput = true;   //特别注意     Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));//特别注意     Response.Cache.SetCacheability(HttpCacheability.NoCache);//特别注意     Response.AppendHeader("Pragma", "No-Cache"); //特别注意    string  VNum  =MakeValidateCode( );    Session["VNum"]=VNum;//取得验证码,以便后来验证    ValidateCode(VNum);}public void ValidateCode(string VNum){validateimage = new Bitmap(60, 20, PixelFormat.Format24bppRgb);g = Graphics.FromImage(validateimage);g.FillRectangle(new LinearGradientBrush(new Point(0,0), new Point(110,20), Color.FromArgb(240,255,255,255),Color.FromArgb(240,255,255,255)),0,0,200,200); //矩形框g.DrawString(VNum, new Font("arial",11),new SolidBrush(Color.Red),new PointF(6,0));//字体/颜色g.Save();MemoryStream ms=new MemoryStream();validateimage.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);Response.ClearContent();Response.ContentType="image/bmp";Response.BinaryWrite(ms.ToArray());Response.End();}

    string MakeValidateCode(){char[] s = new char[]{'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'};//枚举数组string num = "";Random r = new Random();for(int i = 0; i < 5; i++){num += s[r.Next(0, s.Length)].ToString(); } return num;}</script>,那显示出来之后,用户输入到文本框,提交,就需要检验一下验证码是否正确,在login.aspx.cs中:

                if (checkcode == Session["VNum"].ToString() || Session["VNum"].ToString() == null) { }//注意Session["VNum"].ToString(),必须加上ToString(),因//为Session["VNum"]是对象。            //要做的事情            else            {                Message.Text = "验证码错误或为空!";                founderr = true;            }

    这样,就完成了 验证码的生成以及验证。 


    最新回复(0)