一般处理程序制作的验证码

一、新建一个ValidateCode.ashx文件

<%@ WebHandler Language="C#" class="ValidateCode"Debug="true" %>

//Debug="true"是加上去的

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.SessionState;//

public class ValidateCode : IHttpHandler,IRequiresSessionState{     //要使用Session必须使用命名空间里的接口IRequiresSessionState
      public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/jpeg";
        //context.Response.Write("Hello World"+MakeRandomNum());测试生成随机验证码
   //创建验证图片
    string vCode=MakeRandomNum();
    context.Session["vcode"] = vCode;//给Session里写验证码值
    using (Bitmap img = new Bitmap(80,30))
      {
       using (Graphics g = Graphics.FromImage(img))
        {
          g.DrawString(vCode,new Font("微软雅黑",16),Brushes.White,10,2);
          img.Save(context.Response.OutputStream,ImageFormat.Jpeg);
         }
       }
      }
    //生成随机验证码
    public string MakeRandomNum()
    {
        Random ran = new Random();
        string resNum = string.Empty;
        for (int i = 0; i < 4; i++)
        {
            resNum += ran.Next(9).ToString();
        }
        return resNum;
    }
      public bool IsReusable {
        get {
            return false;
             }
       }
}

二、登陆页面:一般处理程序制作的验证码.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="一般处理程序制作的验证码.aspx.cs" Inherits="一般处理程序制作的验证码" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
      
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
         <img src="一般处理程序制作的验证码.ashx" onclick="this.src='一般处理程序制作的验证码.ashx?aaa='+new Date()"/>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="登录" />
   
    </div>
    </form>
</body>
</html>

三、登陆页面一般处理程序制作的验证码.aspx.cs  到Session读值判断验证码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class 一般处理程序制作的验证码 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      
            string session =Convert.ToString(Session["vcode"]);
            if (session == TextBox3.Text)
            {
              
                Response.Write("正确");
            }
            else
            {
                Response.Write("错误");
            }
       
    }
}

posted @ 2012-07-28 14:56  惬意的小屋  阅读(188)  评论(0编辑  收藏  举报