博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net 实现验证码

Posted on 2008-10-31 14:22  Sunny Xu  阅读(254)  评论(0编辑  收藏  举报

要为一个页面添加验证码功能,首先要写一个新的页面用来生产验证码。在这里我们假设验证码生成的页面为LoginCheckCode.aspx,主页面为Login.aspx。验证码生成代码如下:

   protected void Page_Load(object sender, EventArgs e)
        {
            Session.Clear();
            this.GenImage(this.GenCode(4));
            Session["image"] = this.GenCode(4);
        }
        private string GenCode(int num)
        {
            string[] source = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "h", "i", "k", "l", "m", "n", "r", "s", "t", "u", "v", "w", "x", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
            string code = "";
            Random rd = new Random();
            for (int i = 0; i < num; i++)
            {
                code += source[rd.Next(0, source.Length)];
            }
            return code;
        }
        private void GenImage(string code)
        {
            Bitmap myPalette = new Bitmap(70, 20);
            Graphics gh = Graphics.FromImage(myPalette);
            Rectangle rc = new Rectangle(0, 0, 70, 20);
            gh.FillRectangle(new SolidBrush(Color.White), rc);
            gh.DrawString(code, new Font("Arial", 16), new SolidBrush(Color.Green), rc);
            myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            gh.Dispose();
            myPalette.Dispose();
        }

在主页面Login.aspx内只要加上以下代码即可:

            <div id="DivCheckCodeLabel">
                验证码:
            </div>
            <div>
                <input id="InputCheckCode" style="width: 60px" onkeydown="onInputTextCheckCodeClick()" />
                <img id="ImageCheckCode" src="LoginCheck.aspx" alt="点击更新" onclick="this.src = 'LoginCheck.aspx?dc=' + new Date()" />
            </div>

onclick事件实现了验证码的局部刷新功能。

安全起见,判断验证验证代码需要写在后台:

[webMethod]

 public static bool ValidateCheckCode(string checkCodeInput)

{

       string checkCodeSession = HttpContext.Current.Session["image"].ToString();
            if (!checkCodeInput.Equals(checkCodeSession))
                return LoginResultState.WrongCheckCode;

}

其中输入的验证码是在页面调用后台验证函数时作为参数传进去的。这里用到了ajax技术。如果是简单页面,可以直接在后台写onclick事件时比较而不用webMethod方法了。