A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© ♂张耕明 中级黑马   /  2012-11-10 21:58  /  1809 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 ♂张耕明 于 2012-11-10 22:00 编辑
  1. public class Handler : IHttpHandler, IRequiresSessionState//如果要在一般处理程序中使用Session,必须实现 IRequiresSessionState接口。
  2.     {   
  3.         public void ProcessRequest(HttpContext context)
  4.         {
  5.             context.Response.ContentType = "image/JPEG";//指出响应内容的类型。
  6.             using (Bitmap bitmap = new Bitmap(100, 50))//初始化一张位图,使用Graphics在这张位图上进行绘制。
  7.             {   
  8.                 using (Graphics g = Graphics.FromImage(bitmap))
  9.                 {
  10.                     Random random = new Random();
  11.                     int code = random.Next(0, 101);//生成一个0~100的随机数。
  12.                     HttpContext.Current.Session["code"] = code.ToString();//为当前HTTP请求设置Session。
  13.                     g.DrawString(code.ToString(), new Font("微软雅黑", 29), Brushes.Red, new PointF(0, 0));
  14.                     bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);//将此图像以指定的格式保存到指定的流中。
  15.                 }
  16.             }
  17.         }
  18.   }
  19. <form id="form1" runat="server">//当图片加载的时候,会在当前页面设置Session。
  20.   <!-- 点击图片的时候,图片的src属性的值在不变的情况下浏览器不会重新发出请求。-->
  21.   <div><img src="Handler.ashx" alt="验证码" title="验证码" onclick="this.src='Handler.ashx?'+new Date()"/></div>
  22.     <asp:TextBox ID="TextBox" runat="server"></asp:TextBox>
  23.   <asp:Button ID="Button" runat="server" onclick="Button_Click" Text="Button" />
  24.          protected void Button_Click(object sender, EventArgs e)//每点一次服务器控件中的Button都会对页面进行一次重绘。
  25.         {   
  26.             string 正确的验证码 = Session["code"].ToString();
  27.             if (正确的验证码 == TextBox.Text)//判断填入的数值是否和存入的Session值相同。
  28.             {
  29.                 Response.Write("正确!");
  30.             }
  31.             else
  32.             {
  33.                 Response.Write("错误!");
  34.             }
  35.         }
复制代码

评分

参与人数 1技术分 +1 收起 理由
张文 + 1

查看全部评分

3 个回复

倒序浏览
值得学习ing!
回复 使用道具 举报
好教程!!
回复 使用道具 举报
好东西,赞一个
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马