asp.net 前端登录功能详细解析

本文深入探讨了BS架构下系统登录界面的三大核心功能:验证码校验、用户名密码验证及记住我功能。详述了前端布局与异步提交流程,以及后端服务器端的验证码、用户认证逻辑和记住我功能实现。

在BS开发中 系统登录主界面主要有3个功能的开发
1、验证码是否输入正确
2、用户名和密码是否正确
3、记住我功能
以下对其进行详细说明
前端
主要在表单中布置2个文本框1个密码框 用于输入用户名密码和验证码1个img标签存入验证码 1个a标签 更换验证码 1个sumbit提交按钮
前端采用异步提交的方式代码如下

    <script type="text/javascript">
        $(function () {
            checkvCode();//此方法刷新验证码
            $('#btnLogin').click(function () {
                //向服务器端提交请求          序列化表单把数据传递到服务器端
                $.post('LoginCustomers.ashx', $('form').serialize(), function (msg) {
                    //成功相应的回调函数值
                    if (msg == '1') {
                        //返回1代码用户名密码输入正确转到主页面
                        window.location.href = 'Index.aspx';
                    }
                    else {
                        //刷新验证码
                        $('#img1').attr('src', $('#img1').attr('src') + '1');
                        //验证码值为空
                        $('#vCode').val('');
                        //弹出服务器端返回的提示信息
                        alert(msg);                    
                    }
                })
            });
        });
        function checkvCode() {
            //点击看不清换一张的时候刷新验证码
            $('#btnCheck').click(function () {
                //获取img标签的 src属性 对验证码的地址链接+‘1’
                $('#img1').attr('src', $('#img1').attr('src') + '1');
            });
        }
    </script>

后台服务器端代码 判断验证码 用户名和密码,记住我功能都在服务器端实现

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

namespace Maticsoft.Web
{
    /// <summary>
    /// LoginCustomers1 的摘要说明
    /// </summary>
    public class LoginCustomers1 : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string msg = "";
            //判断是否按了提交按钮,
            if (!string.IsNullOrEmpty(context.Request["vCode"]))
            {
                //判断输入的验证码是否一致  在一般处理程序中使用Session需继承IRequiresSessionState接口方可使用
                if (!context.Session["ValidateCode"].ToString().Equals(context.Request["vCode"]))
                {
                    msg = "验证码输入不正确请从新输入!";
                }
                else
                {
                    //调用业务逻辑层
                    Maticsoft.BLL.CustomersInfo cibll = new BLL.CustomersInfo();
                    //获取用户名和密码,
                    string cname = context.Request["uname"];
                    
                    int cid = 0;
                    //密码项采用MD5加密后与数据库中字段进行验证
                    
                    string pwd = Maticsoft.Common.MD5Encypt.GetMd5String(context.Request["pwd"]);
                    string pwd1 = context.Request["pwd"];
                    //如果登录成功
                    if (cibll.LoginCustomersName(cname, pwd,out cid))
                    {
                        //返回主键ID记录到session中用户判断是否登录
                        context.Session["Cid"] = cid;
                        //用户名密码输入正确向客户端返回"1"
                        msg = "1";
                        //把用户名和密码以加密的形式写入到cookie中
                        string temp = cname + "|" + pwd1;
                        //把用户名和密码转换成一个byte数组用于加密
                        byte[] buffer = Encoding.UTF8.GetBytes(temp);
                        //创建一个cookie对象 采用Base64加密方式对其进行加密
                        HttpCookie cookie = new HttpCookie("rm",Convert.ToBase64String(buffer));
                        //如果选中了记住我则把cookie存入到浏览器缓存中
                        if (context.Request["rMe"] != null)
                        {
                            //设置存入的时间为14天
                            cookie.Expires = DateTime.Now.AddDays(14);
                        }
                        
                        else
                        {
                            //如果没选中则清空cookie
                            cookie.Expires = DateTime.Now.AddDays(-1);
                        }
                        //添加cookie
                        context.Response.Cookies.Add(cookie);
                    }
                    else
                    {
                        msg = "用户名密码错误请从新输入!";
                    }
                }
            }
            context.Response.Write(msg);
        }

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

向前端输出cookie这里用一个aspx实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
namespace Maticsoft.Web
{
    public partial class LoginCustomers : System.Web.UI.Page
    {
        protected string Cname { get; set; }//在前端输出用户名
        protected string Cpwd { get; set; }//在前端输出密码
        protected void Page_Load(object sender, EventArgs e)
        {
            //获取cookie对象
            HttpCookie cookies = Request.Cookies["rm"];         
            if (cookies!=null)
            {
                //对获取到的cookie的值中的用户名和密码进行解密
                byte[] buffer = Convert.FromBase64String(cookies.Value);
                //把解密后的数组按照加密的编码格式转换成一个字符串
                string temp = Encoding.UTF8.GetString(buffer);
                //通过"|"进行分割后获取用户名和密码
                string[] temps = temp.Split('|');
                Cname = temps[0];
                Cpwd = temps[1];
            }
        }
    }
}

MD5加密算法

 public static string GetMd5String(string str)
     {
         StringBuilder sb = new StringBuilder();
         MD5 md5 = MD5.Create();

         byte[] buffer = Encoding.UTF8.GetBytes(str);

         byte[] newbuffer = md5.ComputeHash(buffer);

         for (int i = 0; i < newbuffer.Length; i++)
         {
             sb.Append(newbuffer[i].ToString("x"));
         }
         
         return sb.ToString();
     }

动态生成验证码的一个算法

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace Maticsoft.Web
{
    /// <summary>
    /// ValidateCode 的摘要说明
    /// </summary>
    public class ValidateCode : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";
            //设置验证码长度为4
            int codeLength = 4;
            //设置验证码内容
            string sourceString = "abcdef0123456789";

            string temp = "";
            //创建一个4位的随机验证码
            Random r = new Random();
            for (int i = 0; i < codeLength; i++)
            {
                temp += sourceString[r.Next(0, sourceString.Length)];
            }
            //这里将随机的验证码的值直接存入到session中
            context.Session["ValidateCode"] = temp;
            //将验证码写入到图片中
            Bitmap bitmap = new Bitmap(50, 20);
            
            Graphics g = Graphics.FromImage(bitmap);
            g.Clear(Color.White);
            g.DrawRectangle(new Pen(Color.Black), 0, 0, bitmap.Width - 1, bitmap.Height - 1);
            g.DrawString(temp, new Font("Consolas", 14), new SolidBrush(Color.Blue), 0, 0, new StringFormat(StringFormatFlags.LineLimit));
            //把验证码保存到输出流中
            bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);
            
        }

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

验证是否进行了登录自定义一个类名称为pages

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

namespace Maticsoft.Web
{
    //创建一个类继承page类用于校验是否进行了登录
    public class Pages:System.Web.UI.Page
    {      
       public void  Page_Init(object sender, EventArgs e)
       {
           //如果没登录则转到登录页面
           if (Session["Cid"]==null)
           {
               Response.Redirect("LoginCustomers.aspx");
           }
       }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值