当前位置:编程学习 > C#/ASP.NET >>

有关登录验证码

我想要登录时,账号密码还有验证码正确才能登录,用账号密码登录这个后台我写好了,就差验证码部分,请问下验证码部分后台要怎么写呢? --------------------编程问答-------------------- 验证码我弄好了,就差输入显示的验证码,要正确才能登录这部分 --------------------编程问答--------------------
什么问题啊? --------------------编程问答-------------------- 就是要实现登录时输入图片内的验证码正确才能登录,要怎么写? --------------------编程问答-------------------- protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("server=(local);database=zhanghao;uid=sa;pwd=ettoys;");
            con.Open();
            string sql = "select top 1 * from zhang where userName='" + TextBox1.Text + "' and password='" + TextBox2.Text + "'";
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(sql, con); da.Fill(dt);


            
            if (dt.Rows.Count > 0)
            {
                Session["userName"] = TextBox1.Text; Response.Write("<script>alert('恭喜你,登录成功,正在进入中...');window.location='../WebForm5.aspx'</script>");
            }
            else
            {
                 Response.Write("<script>alert('登陆账号或密码错误!!');</script>");
            }
        }

这是后台登录代码,请问下要验证下验证正确才能登录,要怎么加? --------------------编程问答-------------------- 生成验证码时记录在Session里,登录的时候,比较一下输入的验证码和存在Session里的验证码。 --------------------编程问答-------------------- 后台这里要怎么写呀? --------------------编程问答-------------------- 请教啊,谁教教 --------------------编程问答-------------------- 新建页面后台代码:
   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            int length = 5; //五位
            this.CreateCheckCodeImage(GenerateRandomNumber(length));
        }
    }
#region 一组5位随机数(包括全部字符)
    private string GenerateCheckCode()
    {
        int number;
        char code;
        string checkCode = String.Empty;
        System.Random random = new Random();

        for (int i = 0; i < 5; i++)
        {
            number = random.Next();

            if (number % 2 == 0)
                code = (char)('0' + (char)(number % 10));
            else
                code = (char)('A' + (char)(number % 26));

            checkCode += code.ToString();
        }
        Session["ValidateCode"] = checkCode;
        return checkCode;
    }
    #endregion

    #region 设置成图片
    private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode == null || checkCode.Trim() == String.Empty)
            return;
        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
        Graphics g = Graphics.FromImage(image);
        try
        {
            //生成随机生成器
            Random random = new Random();
            //清空图片背景色
            g.Clear(Color.White);
            //画图片的背景噪音线
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);
            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
    #endregion
然后登陆页面的js:
   <script language="javascript" type="text/javascript">
        function ShowNew() {
            var img1 = document.getElementById("imgCode");
            img1.src = "Validate.aspx?" + Math.random();
        }
    </script>
然后:
 验证码:</label><asp:TextBox ID="txtValidate" runat="server" CssClass="input" Width="110px"></asp:TextBox>
                        <img id="imgCode" style="line-height: 22px;" src="SystemMag/Validate.aspx" alt="验证码"
                            onclick="ShowNew();" />
然后你自己在做下判断:
  if (Session["ValidateCode"] != null)
                        {
                            //获取图片上的验证码
                            string code = Session["ValidateCode"].ToString();
                            //判断输入的验证码是否正确,不区分大小写
                            int result = string.Compare(validateCode, code, true);
                       } --------------------编程问答-------------------- 后台代码:
    
protected void btnLoad_Click(object sender, EventArgs e)
    {
        if (String.Compare(txtName.Text.Trim(), "", false) == 0 || String.Compare(txtPassword.Text.Trim(), "", false) == 0)
        {
            lbError.Text = "请填写用户名和密码!";
        }
        else if (String.Compare(txtValid.Text.Trim(), "", false) == 0)
        {
            lbError.Text = "请输入验证码!";
            txtValid.Focus();
        }
        else
        {
            if (Session["RandomCode"] == null)
            {
                lbError.Text = "验证码不正确!";
            }
            //检查验证码(不区分大小写)
            else if (String.Compare(txtValid.Text.ToLower().Trim(), Session["RandomCode"].ToString().ToLower(), false) == 0)
            { 
                //检查用户名和密码是否正确
                int iCheckUser = UserInfo.iCheckUser(txtName.Text.Trim(), txtPassword.Text.Trim());
                //用户名和密码正确
                if (iCheckUser == 1)
                {   
                   //执行登录过程             
                }
                //用户名或密码不正确
                else if (iCheckUser == -1 || iCheckUser == 0)
                {
                    lbError.Text = "用户名或密码不正确!";
                }
            }
            else
            {
                lbError.Text = "验证码错误!<br />看不清验证码?请点击验证码图片刷新。";
            }
        }        
    }


前台代码:

    <div class="lgline lbError"><asp:Label id="lbError" runat="server"></asp:Label></div>
    <div class="lgline">
        <div class="lglb">用户名</div>
        <div class="lginput">
            <asp:TextBox id="txtName" CssClass="txtbox" runat="server" MaxLength="30"></asp:TextBox>
        </div>
    </div>
    <div class="lgline">
        <div class="lglb mr22">密   码</div>
        <div class="lginput"><asp:TextBox id="txtPassword" CssClass="txtbox" runat="server" MaxLength="16" TextMode="Password"></asp:TextBox></div>
    </div>
    <div class="lgline">
        <div class="lglb">验证码</div>
        <div class="lginput">
            <div class="lginput">
                <asp:TextBox id="txtValid" CssClass="txtbox txtValid" runat="server" MaxLength="4"></asp:TextBox>
                <img id="imgValid" style="padding-top:2px;" align="middle" onclick="showimg();" alt="刷新验证码" src="CreateCode.aspx" runat="server" />
            </div>
        </div>
    </div>

    <div class="btnar">
        <asp:Button ID="btnLoad" CssClass="btn" runat="server" ForeColor="White" Text="登 录" OnClick="btnLoad_Click" Height="34px" Width="97px" CausesValidation="False" Font-Size="14px" BorderStyle="None" />
        <asp:Button ID="btnReg" CssClass="btn" runat="server" ForeColor="White" Text="注 册" OnClick="btnReg_Click" Height="34px" Width="97px" CausesValidation="False" Font-Size="14px" BorderStyle="None" />                                                     
    </div>

    <script type="text/javascript"> 
         
    function showimg()
    {
        var im=document.getElementById("<%=imgValid.ClientID %>");
        
        im.src="CreateCode.aspx?"+new Date;                  
    }     
    </script>
    <script language="javascript" type="text/javascript" defer="defer">
        showimg();        
    </script>    


CreateCode.aspx是用于生成验证码图片的页面
示例代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        //将生成的验证码保存到Session中,
        Session["RandomCode"] = 调用生成验证码函数,返回String;
        //生成验证码图片
        CreateImage(Session["RandomCode"].ToString());
    }

    //生成验证码图片
    public void CreateImage(string code)
    {
        Bitmap image = new Bitmap(70, 24);
        Graphics g = Graphics.FromImage(image);
        WebColorConverter ww = new WebColorConverter();
        g.Clear((Color)ww.ConvertFromString("#B3F97A"));

        Random random = new Random();
        //画图片的背景噪音线
        
        for (int i = 0; i < 12; i++)
        {
            int x1 = random.Next(image.Width);
            int x2 = random.Next(image.Width);
            int y1 = random.Next(image.Height);
            int y2 = random.Next(image.Height);
            g.DrawLine(new Pen(Color.WhiteSmoke), x1, y1, x2, y2);
        }

        Font font = new Font("Arial", 14, FontStyle.Bold | FontStyle.Italic);
        System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(
        new Rectangle(0, 0, image.Width, image.Height), Color.FromArgb(0x33, 0x33, 0xFF), Color.Gray, 1.2f, true);
        g.DrawString(code, font, brush, 0, 0);

        //画图片的前景噪音点
        /*
        for (int i = 0; i < 10; i++)
        {
            int x = random.Next(image.Width);
            int y = random.Next(image.Height);
            image.SetPixel(x, y, Color.White);
        }
        */
        //画图片的边框线
         g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        Response.ClearContent();
        Response.ContentType = "image/Gif";
        Response.BinaryWrite(ms.ToArray());
        g.Dispose();
        image.Dispose();
    }
--------------------编程问答-------------------- 生成验证码我自己弄好了,文件名是CheckCode.aspx
 
这是我后台登录的代码
protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("server=(local);database=zhanghao;uid=sa;pwd=ettoys;");
            con.Open();
            string sql = "select top 1 * from zhang where userName='" + TextBox1.Text + "' and password='" + TextBox2.Text + "'";
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(sql, con); da.Fill(dt);


            
            if (dt.Rows.Count > 0)
            {
                Session["userName"] = TextBox1.Text; Response.Write("<script>alert('恭喜你,登录成功,正在进入中...');window.location='../WebForm5.aspx'</script>");
            }
            else
            {
                 Response.Write("<script>alert('登陆账号或密码错误!!');</script>");
            }
        }

我是想问要在这里加什么来判断验证码是否正确,要怎么写?谢谢啦 --------------------编程问答--------------------
引用 10 楼 qldn19966 的回复:
生成验证码我自己弄好了,文件名是CheckCode.aspx
 
这是我后台登录的代码
protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("server=(local);datab……

贴出你的验证码方法,,, --------------------编程问答--------------------
  //获取图片上的验证码
   string code = Session["ValidateCode"].ToString();
   //判断输入的验证码是否正确,不区分大小写
  int result = string.Compare(文本框输入的值, code, true);
if(result == 0)
{
}
else
{
//验证码输入错误,请重新输入
}
--------------------编程问答-------------------- protected void Page_Load(object sender, EventArgs e)
        {
            this.CreateCheckCodeImage(GenerateCheckCode());
        }
        #region Web 窗体设计器生成的代码
        override protected void OnInit(EventArgs e)
        {
            //         
            // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。        
            // 
            InitializeComponent();
            base.OnInit(e);
        }
        /// <summary>     
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改     
        /// 此方法的内容。    
        /// 
        /// </summary> 
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion
        private string GenerateCheckCode()
        {
            int number;
            char code;
            string checkCode = String.Empty;
            System.Random random = new Random();
            for (int i = 0; i < 5; i++)
            {
                number = random.Next();
                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('A' + (char)(number % 26));
                checkCode += code.ToString();
            }
            Session["VNum"] = checkCode;
            return checkCode;
        }
        private void CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
            System.Drawing.Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器             
                Random random = new Random();
                //清空图片背景色             
                g.Clear(Color.White);
                //画图片的背景噪音线             
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);
                //画图片的前景噪音点             
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线             
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                Response.ClearContent();
                Response.ContentType = "image/Gif";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
     --------------------编程问答-------------------- 除 --------------------编程问答--------------------
引用 13 楼 qldn19966 的回复:
protected void Page_Load(object sender, EventArgs e)
        {
            this.CreateCheckCodeImage(GenerateCheckCode());
        }
        #region Web 窗体设计器生成的代码
        override p……


引用 8 楼 lijingye0911 的回复:
新建页面后台代码:
   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheabi……

你好好看看我给你发的8L的代码,跟你的差不多啊,
你的Session["VNum"]这里边就是保存的验证码吧,
然后,你在根据12L给你的代码,进行判断 --------------------编程问答-------------------- 都是大神级别人物,本人初学中~~~学习学习 --------------------编程问答-------------------- <img src="验证码.aspx"> --------------------编程问答--------------------
http://blog.csdn.net/zhoufoxcn/article/details/1698615
引用周公的博客。 --------------------编程问答-------------------- --------------------编程问答--------------------
引用 1 楼 qldn19966 的回复:
验证码我弄好了,就差输入显示的验证码,要正确才能登录这部分

验证码你自己写的还是第三方控件? --------------------编程问答-------------------- 自己搜索一下就有了,很多网站有现成的验证码,要控件也可以。原理就是用SESSION对比。
补充:.NET技术 ,  ASP.NET
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,