用Session实现验证码

新建一个 ashx 一般处理程序 如: YZM.ashx
继承接口 IRequiresSessionState //在一般处理程序里面继承

HttpContext context
为请求上下文,包含此次请求处理要使用到的信息和对象都在里面,有Response,有Request


下面为 YZM.ashx网页内容:

public class YZM : IHttpHandler,System.Web.SessionState.IRequiresSessionState {  
 public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "image/JPEG";  //设置格式为 图片
     using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(55, 25))  //新建一张图片,设置宽度与高度
     { 
       using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
        {
          Random rand = new Random();         //创建一个 随机数类
          int code = rand.Next(1000, 9999);   //获得一个随机数,指定范围
          string strCode = code.ToString();
          HttpContext.Current.Session["Code"] = strCode;  //将随机数赋值给 Session
          g.DrawString(strCode,new System.Drawing.Font("宋体",15),System.Drawing.Brushes.Red,new System.Drawing.PointF(0,0));                //利用随机数创建一个图片,设置大小,颜色
          bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);  
                               //保存图片并输出
            }
        }
    }

下面为WEB页面的代码内容:

  protected void Button1_Click(object sender, EventArgs e)
    {
        string code =Convert.ToString( Session["Code"]);  //得到Session值,验证码值 
        if (code == TextBox3.Text)              //判断验证码
        {
            if (TextBox1.Text == "admin" && TextBox2.Text == "gao")
            {
                Label1.Text = "登录成功";
            }
            else
            {
                Label1.Text = "登录失败";
            }
        }
        else
        {
            Label1.Text = "验证码错误!";
        }
    }

下面为WEB页面的设计内容:

<img alt="" src="YZM.ashx" />    //插入验证码
原文地址:https://www.cnblogs.com/xgao/p/4173965.html