C#验证码的创建与使用示例
本文实例讲述了C#验证码的创建与使用方法。分享给大家供大家参考,具体如下:
1、C#创建验证码
①创建获取验证码页面(ValidateCode.aspx)
<htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server"> <title>获取验证码</title> </head> <body> <formid="form1"runat="server"> <div>获取验证码</div> </form> </body> </html>
②编写获取验证码代码(ValidateCode.aspx.cs)
///<summary> ///验证码类型(0-字母数字混合,1-数字,2-字母) ///</summary> privatestringvalidateCodeType="0"; ///<summary> ///验证码字符个数 ///</summary> privateintvalidateCodeCount=4; ///<summary> ///验证码的字符集,去掉了一些容易混淆的字符 ///</summary> char[]character={'2','3','4','5','6','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','R','S','T','W','X','Y'}; protectedvoidPage_Load(objectsender,EventArgse) { //取消缓存 Response.BufferOutput=true; Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1)); Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AppendHeader("Pragma","No-Cache"); //获取设置参数 if(!string.IsNullOrEmpty(Request.QueryString["validateCodeType"])) { validateCodeType=Request.QueryString["validateCodeType"]; } if(!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"])) { int.TryParse(Request.QueryString["validateCodeCount"],outvalidateCodeCount); } //生成验证码 this.CreateCheckCodeImage(GenerateCheckCode()); } privatestringGenerateCheckCode() { charcode; stringcheckCode=String.Empty; System.Randomrandom=newRandom(); for(inti=0;i<validateCodeCount;i++) { code=character[random.Next(character.Length)]; //要求全为数字或字母 if(validateCodeType=="1") { if((int)code<48||(int)code>57) { i--; continue; } } elseif(validateCodeType=="2") { if((int)code<65||(int)code>90) { i--; continue; } } checkCode+=code; } Response.Cookies.Add(newSystem.Web.HttpCookie("CheckCode",checkCode)); this.Session["CheckCode"]=checkCode; returncheckCode; } privatevoidCreateCheckCodeImage(stringcheckCode) { if(checkCode==null||checkCode.Trim()==String.Empty) return; System.Drawing.Bitmapimage=newSystem.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*15.0+40)),23); System.Drawing.Graphicsg=System.Drawing.Graphics.FromImage(image); try { //生成随机生成器 Randomrandom=newRandom(); //清空图片背景色 g.Clear(System.Drawing.Color.White); //画图片的背景噪音线 for(inti=0;i<25;i++) { intx1=random.Next(image.Width); intx2=random.Next(image.Width); inty1=random.Next(image.Height); inty2=random.Next(image.Height); g.DrawLine(newSystem.Drawing.Pen(System.Drawing.Color.Silver),x1,y1,x2,y2); } System.Drawing.Fontfont=newSystem.Drawing.Font("Arial",14,(System.Drawing.FontStyle.Bold|System.Drawing.FontStyle.Italic)); System.Drawing.Drawing2D.LinearGradientBrushbrush=newSystem.Drawing.Drawing2D.LinearGradientBrush(newSystem.Drawing.Rectangle(0,0,image.Width,image.Height),System.Drawing.Color.Blue,System.Drawing.Color.DarkRed,1.2f,true); intcySpace=16; for(inti=0;i<validateCodeCount;i++) { g.DrawString(checkCode.Substring(i,1),font,brush,(i+1)*cySpace,1); } //画图片的前景噪音点 for(inti=0;i<100;i++) { intx=random.Next(image.Width); inty=random.Next(image.Height); image.SetPixel(x,y,System.Drawing.Color.FromArgb(random.Next())); } //画图片的边框线 g.DrawRectangle(newSystem.Drawing.Pen(System.Drawing.Color.Silver),0,0,image.Width-1,image.Height-1); System.IO.MemoryStreamms=newSystem.IO.MemoryStream(); image.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); Response.ClearContent(); Response.ContentType="image/Gif"; Response.BinaryWrite(ms.ToArray()); } finally { g.Dispose(); image.Dispose(); } }
2、验证码的使用
①验证码的前段显示代码
<imgsrc="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309"onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();"id="imgValidateCode"alt="点击刷新验证码"title="点击刷新验证码"style="cursor:pointer;">
②创建验证码测试页面(ValidateTest.aspx)
<htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server"> <title>验证码测试</title> </head> <body> <formid="form1"runat="server"> <div> <inputrunat="server"id="txtValidate"/> <imgsrc="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309"onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();"id="imgValidateCode"alt="点击刷新验证码"title="点击刷新验证码"style="cursor:pointer;"> <asp:Buttonrunat="server"id="btnVal"Text="提交"onclick="btnVal_Click"/> </div> </form> </body> </html>
③编写验证码测试的提交代码(ValidateTest.aspx.cs)
protectedvoidbtnVal_Click(objectsender,EventArgse) { boolresult=false;//验证结果 stringuserCode=this.txtValidate.Value;//获取用户输入的验证码 if(String.IsNullOrEmpty(userCode)) { //请输入验证码 return; } stringvalidCode=this.Session["CheckCode"]asString;//获取系统生成的验证码 if(!string.IsNullOrEmpty(validCode)) { if(userCode.ToLower()==validCode.ToLower()) { //验证成功 result=true; } else { //验证失败 result=false; } } }
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#图片操作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》
希望本文所述对大家C#程序设计有所帮助。