ASP.NET 图片验证码登陆代码

图片验证代码主要包括两个部分,登陆部分和图片验证码加载部分。

1.登陆前台部分如下:Login.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>用户登录</title>
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
    <link href="Style/cs.css" rel="stylesheet" type="text/css" />


    <script src="js/webutil.js" type="text/javascript"></script>


    <style type="text/css">
        *
        {
            margin: 0px auto;
            padding: 0px;
        }
        body
        {
            background: #ffffff url(images/LoginIn/logbg.gif) repeat-x;
            width: 100%;
            height: 100%;
            font: 12px "宋体";
        }
        .logbg
        {
            background: url(images/LoginIn/logbg.jpg) no-repeat center;
            height: 520px;
            width: 1000px;
            margin-top: 40px;
        }
        .log_txt
        {
            padding-top: 220px;
            width: 280px;
        }
        .text
        {
            margin-bottom: 12px;
            color: #272727;
        }
        .lottext
        {
            border: #9a9b9c 1px solid;
            width: 200px;
            height: 20px;
            line-height: 20px;
            color: #a3c0e8;
        }
        .yanzm
        {
            width: 85px;
            border: #9a9b9c 1px solid;
            height: 20px;
            line-height: 20px;
        }
        .checkbox
        {
            margin-left: 40px;
        }
        .bott
        {
            clear: both;
            margin-top: 0px;
            margin-left: 50px;
        }
        .foonter
        {
            text-align: center;
            color: #262727;
            margin-top: 40px;
            margin-left: 30px;
            line-height: 25px;
        }
        .jiz
        {
            color: #262626;
            margin-left: 5px;
        }
        .waji
        {
            float: left;
            margin-left: 10px;
            padding-top: 6px;
        }
        .waji a
        {
            color: #003b7f;
            text-decoration: none;
        }
        .text
        {
            margin-top: 10px;
        }
        .text1
        {
            margin-top: 10px;
            margin-left: 35px;
        }
        .dis1
        {
            display: block;
        }
        .undis1
        {
            display: none;
        }
    </style>


    <script src="Js/jquery-1.5.1.min.js" type="text/javascript"></script>


    <script type="text/javascript" language="javascript">
        $(window).load(function() {
            //            alert($("#txtMm").val());
            //            if ($.cookie("GylyUserState") != null) {


            //                alert(123);
            //            }


        });
    
    
    </script>


    <script type="text/javascript">
        function ChangeCode() {
            var date = new Date();
            var myImg = document.getElementById("ImageCheck");
            myImg.src = "ValidateCode.aspx?flag=" + date.getMilliseconds()
            return false;
        }


        function ChangeImg(o) {
            if (o.indexOf("#") != -1) {
                var imgsrc = o.split("#")[0];
                document.getElementById('oImg').src = "images/LoginIn/" + imgsrc;
            }
        }


        function IsNull() {
            var a = document.getElementById("txtYh");
            if (a.value == "用户登录/邮箱登录") {
                document.getElementById("txtYh").value = "";
                document.getElementById("txtYh").style.color = "black";
            }


        }

        window.onload = function() {
            var a = document.getElementById("txtYh");
            if (a.value == "用户登录/邮箱登录") {


                document.getElementById("txtYh").style.color = "#a3c0e8";
            }
            else {
                document.getElementById("txtYh").style.color = "black";
            }


        }
    </script>


</head>


<script language="javascript" type="text/javascript">
    if (window != top)
        top.location.href = location.href; 
</script>


<body>
    <form id="form1" runat="server">
    <div class="logbg">
        <div class="log_txt">
            <div class="text">
                用户名:<asp:TextBox ID="txtYh" runat="server" CssClass="lottext" Style="color: #a3c0e8;"
                    Text="用户登录/邮箱登录" οnfοcus="IsNull()"></asp:TextBox>
            </div>
            <div class="text">
                密&nbsp;&nbsp;码:<asp:TextBox ID="txtMm" runat="server" CssClass="lottext" TextMode="Password"
                    EnableTheming="True"></asp:TextBox>
            </div>
            <div class="text">
                验证码:<asp:TextBox ID="txtYzm" runat="server" CssClass="yanzm"></asp:TextBox>
                <span style="margin-left: 0px;"><a id="A2" href="" οnclick="ChangeCode();return false;"
                    style="height: 21px;">
                    <asp:Image ID="ImageCheck" runat="server" ImageUrl="ValidateCode.aspx" ImageAlign="AbsMiddle"
                        ToolTip="看不清,换一个" Height="21px"></asp:Image>
                </a></span>
            </div>
            <div class="checkbox">
                <p class="jiz">
                    <asp:CheckBox ID="RememberUser" runat="server" Text=" 记住登录状态" /></p>
            </div>
            <div style="color: #e33904; padding-top: 0px; margin-left: 80px;">
                <asp:Label ID="lbXxts" runat="server" Width="120px" Height="16px" Style="text-align: center;
                    padding-top: 0px;"></asp:Label>
            </div>
            <div>
                <p style="float: left;">
                    <asp:ImageButton ID="btnDL" runat="server" CssClass="bott" ImageUrl="images/LoginIn/bottbg.gif"
                        OnClick="btnDL_Click" /></p>
                <p class="waji">
                    <a href="FindPassword.aspx">忘记密码?</a></p>
            </div>
        </div>
        <div class="foonter">
            <p>
                贵阳市生态文明建设委员会</p>
            Copyright<span style="font-family: Arial;">&copy;</span>2012 技术支持:北京东方泰坦科技股份有限公司
        </div>
    </div>
    </form>
</body>
</html>

2.登陆后台程序Login.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Otitan.Web.Func;
using Otitan.BLL;




namespace Otitan.Web
{
    /// <summary>
    /// 功能:用户登录
    /// 创建者:阮林佳
    /// 创建日期:2012-8-28
    /// </summary>
    public partial class Login : System.Web.UI.Page
    {
        BLL.BS_USER b_user = new Otitan.BLL.BS_USER();         //用户表
        Model.BS_USER m_user = new Otitan.Model.BS_USER();
        //页面加载
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //接受cs系统参数登录系统
               
                string user = Request.QueryString["user"] == null ? "" : Request.QueryString["user"].ToString();
                if (user != "")
                {
                    m_user = b_user.GetExtendModel(user);
                    GetState(m_user);
                }
                string username = Request.QueryString["username"];
                string password = Request.QueryString["password"];
                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    CheckState(username, password);
                    return;
                }


                ReadCookie();


            }
        }


        /// <summary>
        /// 读取Cookie,获取登录信息
        /// </summary>
        private void ReadCookie()
        {
            //读取cookie
            HttpCookie aCookie = Request.Cookies["GylyUserState"];
            if (aCookie != null)
            {
                if (aCookie.Values["UserCode"] != null && aCookie.Values["UserCode"].ToString() != "")
                {
                    txtYh.Text = aCookie.Values["UserCode"].ToString();
                }
                //txtMm.Text = Otitan.Common.DEncrypt.DESEncrypt.Decrypt(aCookie.Values["PassWord"].ToString());
                //if (aCookie.Values["PassWord"] != null && aCookie.Values["PassWord"].ToString() != "")
                //{
                //    txtMm.Attributes.Add("Value", Otitan.Common.DEncrypt.DESEncrypt.Decrypt(aCookie.Values["PassWord"].ToString()));
                //    txtMm.Attributes.Add("OnFocus", "this.value=''");
                //}
            }
        }




        /// <summary>
        /// cs到bs判断是否可以登录
        /// </summary>
        /// <param name="p_username">用户名</param>
        /// <param name="p_password">加密后的密码</param>
        protected void CheckState(string p_username, string p_password)
        {
            Otitan.BLL.BS_USER b_user = new BS_USER();
            Otitan.Model.BS_USER m_user = b_user.GetExtendModel(p_username);
            if (m_user != null)
            {
                if (m_user.PASSWORD == p_password)  
                {
                    UserState userstate = new UserState();
                    userstate.M_User = m_user;
                    Session.Add("UserState", userstate);
                    Response.Redirect("SystemSelect.aspx");
                }
            }
        }






        protected void btnDL_Click(object sender, ImageClickEventArgs e)
        {
            Model.BS_USER m_user;
            string usercode = txtYh.Text.Trim();
            if (txtYh.Text != "用户登录/邮箱登录")
            {
                if (usercode == "")
                {
                    lbXxts.Text = "用户名不能为空";
                    txtYzm.Text = "";
                    return;
                }


                if (txtYzm.Text.Trim() == "")
                {
                    lbXxts.Text = "验证码不能为空";
                    return;
                }
                if (Session["CheckCode"] == null || txtYzm.Text.ToLower() != Session["CheckCode"].ToString().ToLower())
                {
                    lbXxts.Text = "验证码不正确";
                    txtYzm.Text = "";
                    return;
                }


                string userpwd = txtMm.Text;
                m_user = b_user.GetExtendModel(usercode);
                if (m_user == null)
                {
                    lbXxts.Text = "用户名不存在";
                    txtYzm.Text = "";
                    return;
                }


                if (m_user.ISACTIVE == 0)
                {
                    lbXxts.Text = "用户未激活";
                    txtYzm.Text = "";
                    return;
                }
                //string mn = Otitan.Common.DEncrypt.DESEncrypt.Decrypt(m_user.PASSWORD);
                if (m_user.PASSWORD != Otitan.Common.DEncrypt.DESEncrypt.Encrypt(txtMm.Text))
                {
                    lbXxts.Text = "密码不正确";
                    txtYzm.Text = "";
                    return;
                }


                if (txtYh.Text == "用户登录/邮箱登录")
                {
                    usercode = "gys_admin";
                }
                else
                {
                    usercode = txtYh.Text;
                }
                m_user = b_user.GetExtendModel(usercode);
            }
            else
            {
                m_user = b_user.GetExtendModel("gys_admin");
            }
            GetState(m_user);


           


        }


        protected void GetState(Model.BS_USER m_user)
        {
            if (m_user != null)
            {
                string usercode = txtYh.Text.Trim();
                UserState userstate = new UserState();
                userstate.M_User = m_user;
                Session.Add("UserState", userstate);


                if (RememberUser.Checked)
                {
                    HttpCookie cookie = new HttpCookie("GylyUserState");
                    cookie.Values.Add("UserCode", usercode);
                   // cookie.Values.Add("PassWord", m_user.PASSWORD);
                    cookie.Expires = DateTime.Now.AddDays(7);
                    Response.Cookies.Add(cookie);


                }
                Response.Redirect("SystemSelect.aspx");
            }
            else
            {
                lbXxts.Text = "用户密码不匹配";
            }
        }


    }
}

3.图片加载程序ValidateCode.aspx.cs

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


namespace Otitan.Web
{
    /// <summary>
    /// 
    /// </summary>
    public partial class ValidateCode : System.Web.UI.Page
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string checkCode = GetRandomCode(4);
            Session["CheckCode"] = checkCode;
            SetPageNoCache();
            CreateImage(checkCode);
        }


        /// <summary>
        /// 设置页面不被缓存
        /// </summary>
        private void SetPageNoCache()
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AppendHeader("Pragma", "No-Cache");
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="codeCount"></param>
        /// <returns></returns>
        private string CreateRandomCode(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;


            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(35);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);//性能问题
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="CodeCount"></param>
        /// <returns></returns>
        private string GetRandomCode(int CodeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
            string[] allCharArray = allChar.Split(',');
            string RandomCode = "";
            int temp = -1;


            Random rand = new Random();
            for (int i = 0; i < CodeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
                }


                int t = rand.Next(33);


                while (temp == t)
                {
                    t = rand.Next(33);
                }


                temp = t;
                RandomCode += allCharArray[t];
            }


            return RandomCode;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="checkCode"></param>
        private void CreateImage(string checkCode)
        {
            int iwidth = (int)(checkCode.Length * 14);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
            Graphics g = Graphics.FromImage(image);
            Font f = new System.Drawing.Font("Arial ", 10);//, System.Drawing.FontStyle.Bold);
            Brush b = new System.Drawing.SolidBrush(Color.Black);
            Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));


            //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
            // g.Clear(Color.AliceBlue);//背景色
            g.Clear(System.Drawing.ColorTranslator.FromHtml("#99C1CB"));//背景色


            char[] ch = checkCode.ToCharArray();
            for (int i = 0; i < ch.Length; i++)
            {
                if (ch[i] >= '0' && ch[i] <= '9')
                {
                    //数字用红色显示
                    g.DrawString(ch[i].ToString(), f, r, 3 + (i * 12), 3);
                }
                else
                {   //字母用黑色显示
                    g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);
                }
            }


            //for循环用来生成一些随机的水平线
            // Pen blackPen = new Pen(Color.Black, 0);
            // Random rand = new Random();
            // for (int i=0;i<5;i++)
            // {
            // int y = rand.Next(image.Height);
            // g.DrawLine(blackPen,0,y,image.Width,y);
            // }


            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            //history back 不重复 
            Response.Cache.SetNoStore();//这一句
            Response.ClearContent();
            Response.ContentType = "image/Jpeg";
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        } 
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是ASP.NET验证码代码: ASPX页面: ```html <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Captcha.aspx.cs" Inherits="Captcha" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Image ID="imgCaptcha" runat="server" /> <br /> <asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox> <asp:Button ID="btnCheck" runat="server" Text="Check" OnClick="btnCheck_Click" /> </div> </form> </body> </html> ``` ASPX.CS页面: ```csharp using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Web.UI; public partial class Captcha : Page { private string GenerateRandomCode(int length) { const string chars = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz123456789"; var random = new Random(); var result = new char[length]; for (var i = 0; i < length; i++) { result[i] = chars[random.Next(chars.Length)]; } return new string(result); } protected void Page_Load(object sender, EventArgs e) { var randomCode = GenerateRandomCode(6); Session["Captcha"] = randomCode; using (var bitmap = new Bitmap(100, 30)) { using (var graphics = Graphics.FromImage(bitmap)) { graphics.Clear(Color.White); graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.DrawString(randomCode, new Font("Arial", 16), Brushes.Black, new Point(10, 0)); Response.ContentType = "image/png"; bitmap.Save(Response.OutputStream, ImageFormat.Png); } } } protected void btnCheck_Click(object sender, EventArgs e) { if (txtCaptcha.Text.Equals(Session["Captcha"])) { Response.Write("Correct!"); } else { Response.Write("Incorrect!"); } } } ``` 这个代码生成一个6位随机验证码,并将其存储在会话中。然后使用Graphics类在ASP.NET页面上绘制验证码图像,并将其发送回客户端。用户输入他们看到的验证码并单击“检查”按钮, ASP.NET代码将会检查用户输入是否与会话中存储的验证码匹配。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值