ASP.NET如何生成验证码
导读:本文共1788.5字符,通常情况下阅读需要6分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 本文实例为大家分享了ASP.NET生成验证码的具体代码,供大家参考,具体内容如下首先,添加一个一般处理程序注释很详细了,有不懂的欢迎评论usingSystem;usingSystem.Collections.Generic;usingSystem.Drawing;usingSystem.Linq;usingSystem.Web;usingSystem.... ...
音频解说
目录
(为您整理了一些要点),点击可以直达。本文实例为大家分享了ASP.NET生成验证码的具体代码,供大家参考,具体内容如下
首先,添加一个一般处理程序
注释很详细了,有不懂的欢迎评论
usingSystem;usingSystem.Collections.Generic;usingSystem.Drawing;usingSystem.Linq;usingSystem.Web;usingSystem.Web.SessionState;namespaceProject_Practice{///<summary>///Handler1的摘要说明///</summary>publicclassHandler1:IHttpHandler,IRequiresSessionState{publicvoidProcessRequest(HttpContextcontext){//选取的颜色Color[]colors={Color.White};//通过Bitmap构造ImageImageimg=newBitmap(100,60);//Graphics绘画ImageGraphicsgraphics=Graphics.FromImage(img);Randomrandom=newRandom(DateTime.Now.Millisecond);//验证码的四位数intcharNum1=random.Next('0','9'+1);intcharNum2=random.Next('0','9'+1);intcharNum3=random.Next('0','9'+1);intcharNum4=random.Next('0','9'+1);//把生成的随机数变成字符串,通过char进行转换stringvalidCode=string.Format($"{(char)charNum1}{(char)charNum2}{(char)charNum3}{(char)charNum4}");//放进Session进行存储,记得继承接口,否则疯狂报空指针context.Session["verification_Code"]=validCode;//字体的大小和类别Fontfont=newFont("宋体",24);//随机的颜色Brushbrush2=newSolidBrush(colors[random.Next(0,colors.Length-1)]);//DrawString的四个参数,第一个是要写的字符,第二个是字体,第三个是颜色,第四个是坐标x,ygraphics.DrawString(((char)charNum1).ToString(),font,brush2,7,-3);Brushbrush3=newSolidBrush(colors[random.Next(0,colors.Length-1)]);graphics.DrawString(((char)charNum2).ToString(),font,brush3,26,-9);Brushbrush4=newSolidBrush(colors[random.Next(0,colors.Length-1)]);graphics.DrawString(((char)charNum3).ToString(),font,brush4,50,0);Brushbrush5=newSolidBrush(colors[random.Next(0,colors.Length-1)]);graphics.DrawString(((char)charNum4).ToString(),font,brush5,70,-7);//保存,格式context.Response.ContentType="image/jpeg";img.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);//释放资源graphics.Dispose();img.Dispose();}publicboolIsReusable{get{returnfalse;}}}}
一个web窗体
<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="verification_Code.aspx.cs"Inherits="Project_Practice.verification_Code"%><!DOCTYPEhtml><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><title></title></head><body><formid="form1"runat="server"><div><asp:ImageID="Image1"runat="server"ImageUrl="~/Handler1.ashx"/></div></form></body></html>
效果图
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:
ASP.NET如何生成验证码的详细内容,希望对您有所帮助,信息来源于网络。