自己动手写验证码

*******************************************处理程序(CheckCode.ashx)***************************/ public class CheckCode : IHttpHandler,System.Web.SessionState.IRequiresSessionState //注意处理程序应用session需要的System.Web.SessionState.IRequiresSessionState接口 {

public void ProcessRequest (HttpContext context) {

context.Response.ContentType = "image/jpeg";

using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(80, 30)) {

using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap)) {

g.DrawString("你好吗",new System.Drawing.Font("宋体",20), System.Drawing.Brushes.Green ,new System.Drawing.PointF(0,0) );

 System.Drawing.Pen pen= (System.Drawing.Pen)System.Drawing.Pens.Red.Clone();

 pen.Width=5;

g.DrawEllipse(pen,new System.Drawing.Rectangle(10,10,10,10)); bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);//上面是自己手写的图片

Random r = new Random();

int random=r.Next(0,9999);

string code = random.ToString();

HttpContext.Current.Session["code"] = code;//数字验证码

byte[] bytes = new byte[100];

Random randObj = new Random();

int code;

for (int i = 0; i < 4; i++) {

code = randObj.Next(44, 122); bytes[i] = Convert.ToByte(code);

}

System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();

string validateCode = ascii.GetString(bytes, 0, 4);

string strcode= validateCode.ToString();//根据ASCII码随机获取的验证码

g.DrawString(code,new System.Drawing.Font("宋体",20),System.Drawing.Brushes.Green,new System.Drawing.PointF(0,0)); bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

}

} }

/*******************************************页面对验证码的应用***************************/

<form id="form1" runat="server"> <div> <img src="CheckCode.ashx" onclick="this.src='CheckCode.ashx?date='+new Date()" />//点击验证码一次回传给ashx一次,刷新一下验证码(注意参数为时间不会一样的) <br />

</div>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="确定" onclick="Button1_Click" />

</form>

protected void Button1_Click(object sender, EventArgs e) {

if (TextBox1.Text == Session["code"].ToString()) { Response.Write("验证通过!"); } else { Response.Write("验证失败!");

}

}

posted @   创业男生  阅读(278)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示