欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.net 登录账号的验证码功能

程序员文章站 2024-01-24 20:07:52
...

登录前端页面的登录模块如下图所示:

.net 登录账号的验证码功能

前端页面的代码如下:

<table width="380" height="450" border="0" cellpadding="0" cellspacing="0" style="border: 1px solid #B8CACB;">
                                <tr>
                                    <th bgcolor="#F6F6F6" scope="row" style="color: #A7ABDC">
                                        &nbsp;&nbsp;登录
                                    </th>
                                </tr>
                                <tr>
                                    <th bgcolor="#F6F6F6" scope="row">
                                        <input id="txtAccount" runat="server" class="ipt" name="username" size="10" type="text"
                                            style="vertical-align: middle" />
                                    </th>
                                </tr>
                                <tr>
                                    <th bgcolor="#F6F6F6" scope="row">
                                        <input id="txtextAdminPassword" runat="server" class="ipt" name="password" size="10"
                                            type="password" style="vertical-align: middle" />
                                    </th>
                                </tr>
                                <tr>
                                    <th bgcolor="#F6F6F6" scope="row">
                                        <input id="txtValiCode" runat="server" class="ipt" name="authcode" size="10" type="text"
                                            style="vertical-align: middle" />
                                        &nbsp;<img alt="验证码" onclick="this.src='../imgCode.aspx?k='+Math.random()" src="../imgCode.aspx" style="margin-bottom: -10px; height: 30px" />
                                    </th>
                                </tr>
                                <tr>
                                    <th bgcolor="#F6F6F6" scope="row" style="text-align: center">
                                        <asp:ImageButton ID="ImageButton1" runat="server" Height="35px" Width="300px" ImageUrl="Images/imgBtn.png"
                                            OnClick="ImageButton1_Click" />
                                    </th>
                                </tr>
                                <tr>
                                    <th bgcolor="#F6F6F6" scope="row" style="text-align: center; color: Red; font-size: 14px; height:50px;">
                                        <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
                                    </th>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>

最重要的是<img alt="验证码" οnclick="this.src='../imgCode.aspx?k='+Math.random()" src="../imgCode.aspx" style="margin-bottom: -10px; height: 30px" />这段代码,生成的验证码图片存放在img标签中。

调用的imgCode.aspx页面的前端代码如下所示:只留下这开头的一行基础设置信息。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="imgCode.aspx.cs" Inherits="AutomatedValuation.imgCode" %>

imgCode.aspx页面的后端代码如下所示:

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

namespace AutomatedValuation
{
    public partial class imgCode : System.Web.UI.Page
    {
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            this.CreateCheckCodeImage(GenerateCheckCode(), this.Context);
        }


        /// <summary>
        /// 产生随即数验证码并返回
        /// </summary>
        /// <returns></returns>
        public string GenerateCheckCode()
        {
            int number;
            char code;
            string checkCode = String.Empty;
            System.Random random = new Random();
            for (int i = 0; i < 4; i++)
            {
                number = random.Next();
                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('A' + (char)(number % 26));
                checkCode += code.ToString();
            }

            return checkCode;
        }
        /// <summary>
        /// 生成图片
        /// </summary>
        /// <param name="checkCode"></param>
        private void CreateCheckCodeImage(string checkCode, HttpContext hc)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;

            hc.Session["validateCode"] = checkCode;
            hc.Session.Timeout = 600;
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 14.0)), 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);
                hc.Response.ClearContent();
                hc.Response.ContentType = "image/Gif";
                hc.Response.BinaryWrite(ms.ToArray());
                hc.Response.End();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}

返回到登录界面的后端代码如下:

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            lblMessage.Visible = false;

            if (string.IsNullOrEmpty(Session["validateCode"] + ""))
            {
                Request.Cookies.Clear();
                Session.Clear();
                Response.Redirect("Login.aspx");
            }
            if (Session["validateCode"].ToString().ToLower().Equals(this.txtValiCode.Value.ToLower()))
            {
                string userName = this.txtAccount.Value.Trim();
                string password = this.txtextAdminPassword.Value.Trim();

                UsersBLL ubll = new UsersBLL();//这里加上管理员用户的判断

                var user = ubll.GetModel(userName);
                int power = user.UserPower.GetValueOrDefault();
                int level = user.UserLevel.GetValueOrDefault();
                string permission = user.PermissionsJh.ToString();
                if(user != null && user.UPassWord == password  )//管理员权限为3
                {
                    if (power == 3 && level == 3)
                    {
                        //登录成功
                        //Session["UserAccount"] = user.UserAccount;
                        //Session["UPassWord"] = user.UPassWord;
                        //Session["UserName"] = user.UserName;

                        //登录成功
                        Response.Cookies["UserAccount"].Value = HttpUtility.UrlEncode(user.UserAccount, Encoding.GetEncoding("UTF-8"));
                        Response.Cookies["UserID"].Value = HttpUtility.UrlEncode(user.UserID.ToString(), Encoding.GetEncoding("UTF-8"));
                        Response.Cookies["UserAccount"].Expires = DateTime.MaxValue;
                        Response.Cookies["UserID"].Expires = DateTime.MaxValue;
                        Response.Cookies["UserName"].Value = HttpUtility.UrlEncode(user.UserName.ToString(), Encoding.GetEncoding("UTF-8"));
                        Response.Cookies["UserName"].Expires = DateTime.MaxValue;

                        //跳转
                        Response.Redirect("xzxs.aspx");
                    }
                    else
                    {
                        lblMessage.Text = "账户或用户名不对,请重新输入";
                        lblMessage.Visible = true;
                    }
                }
                else
                {
                    lblMessage.Text = "该账户不存在,请先注册";
                    lblMessage.Visible = true;
                }
            }
            else
            {
                lblMessage.Text = "验证码错误";
                lblMessage.Visible = true;
                //Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('验证码错误');", true);
            }
        }