asp.net学习笔记·简单验证码的实现
使用Session进行判断
在一般处理程序中生成验证码,然后设置到Image控件中去,然后与用户输入的数字进行比较,若不正确则重新调用生成验证码,防止暴利破解验证码
此程序仅为个人学习Session做测试,并非专业验证码程序
一般处理程序的代码如下
<%@ WebHandler Language="C#" Class="IdentifyingCode" %> using System; using System.Web; using System.Drawing; using System.Drawing.Imaging; public class IdentifyingCode : IHttpHandler,System.Web.SessionState.IRequiresSessionState //在一般处理程序中要是想使用Session,必须实现System.Web.SessionState.IRequiresSessionState接口,否则会报错说没有此实例 { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; //Bitmap bitmap = new Bitmap(300, 100); Bitmap bitmap = GetImg(); bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg); } /// <summary> /// 生成验证码图片 /// </summary> /// <returns>生成的图片</returns> public Bitmap GetImg() { //产生随机数 Random random = new Random(System.DateTime.Now.Second);//一时间为种子 int num = random.Next(1000, 9999); HttpContext.Current.Session["idenfyCode"] = num;//将生成的数字保存在session中 Bitmap bitMap = new Bitmap(300, 100);//生成图片 Graphics graphics = Graphics.FromImage(bitMap);//画图 graphics.DrawString(num.ToString(), new Font("宋体", 20), new SolidBrush(Color.Blue), new PointF(0, 0)); return bitMap; } public bool IsReusable { get { return false; } } }
然后Web窗体的后台C#代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Drawing; using System.Drawing.Imaging; public partial class IdentifyingCode : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Image1.ImageUrl = "IdentifyingCode.ashx"; } protected void Button1_Click(object sender, EventArgs e) { //将session中保存的数字与用户输入的数据进行比较 if (Session["idenfyCode"].ToString() == TextBox1.Text) { Response.Write("登录成功"); } else { //如果输入验证码错误则重新生成一张验证码,防止暴利破解 this.Image1.ImageUrl = "IdentifyingCode.ashx"; } } }