验证码一般处理程序实现

    通过验证码登录。主体思路:一般处理程序生成验证码,并且保存验证码的值在Session对象中,登录页面取到并判断。

    首先建立一个登录界面Login.aspx。具体内容如代码所示:  

<body>
    <form id="form1" runat="server">
    <div>       
     验证码:
<asp:textbox ID="txtvalidate" runat="server"></asp:textbox> <img alt="" src="ValidateCode.ashx" width="60" height="30"/> <br /> <asp:Button ID="btnLogin" runat="server" Text="登录" onclick="btnLogin_Click" /> </div> </form> </body>

    登录按钮btnLogin_Click事件如下:

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string validate=txtvalidate.Text.Trim();
            if (Session["code"] == null || Session["code"].ToString() != validate)
            {
                Response.Write("<script type='text/javascript'>alert('验证码错误!')</script>");
                return;
            }
       Response.Redirect("Default.aspx");//转到主页
}

    新建ValidateCode.ashx。通过GDI+绘图。在一般应用程序中不能直接使用Session对象,要引入命名空间using System.Web.SessionState。

    并且实现IRequiresSessionState接口

    一般处理程序代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Web.SessionState;

namespace 登录验证
{
    /// <summary>
    /// ValidateCode 的摘要说明
    /// </summary>
    public class ValidateCode : IHttpHandler,IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            using (Bitmap bitmap=new Bitmap(60,30))
            {
                using (Font f=new Font("宋体",20))
                {
                    using (Graphics g=Graphics.FromImage(bitmap))
                    {
                        Random r = new Random();
                        int validata = r.Next(1000,9999);//随机生成四位纯数字的验证码
                        context.Session["code"]=validata;//保存在Session内置对象中
                        g.DrawString(validata.ToString(),f,Brushes.Red,new PointF(0,0));
                    }
                }
                bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

posted @ 2012-10-31 19:36  阿朱姐姐  阅读(383)  评论(0编辑  收藏  举报

友情链接:@开源中国

回到顶部