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