使用C#编写MVC登录页面

在编写项目时,编写了一部分关于登录页面的一些代码,现在和大家分享一下。

使用C#编写MVC登录页面_第1张图片

上图是本篇文章所要实现的样式和效果,可以更换身份,点击登录时跳转到主页面。

  1. 第一步先判断用户ID是否为空,如果不为空就跳转到登录页面。

    public ActionResult Main()
            {
                // 读取session中的用户信息
                if (Session["UserID"] == null)
                {
                    return Redirect("/Main/Login");
                }
                return View();
            }

2.下面代码是登录页面的样式代码

(1)所要引入的文件



    

    登录

    

    

    

(2)body的样式代码

   

 
       
                   
   

(3)js部分



    

    

3. 验证码生成

public ActionResult ValidCode()

        {

            //生成一个随机字符串 验证码

            string strRandom = ValidCodeUtils.GetRandomCode(5);//五位数

            //string strRandom = "123";//验证码为123

            //将验证码存入Session会话

            Session["validCode"] = strRandom;

            //byte[] 根据验证码产生图片

            byte[] imgByte = ValidCodeUtils.CreateImage(strRandom);

            //返回图片信息

            return File(imgByte, @"image/jpeg");

        }

4. 登录验证

public ActionResult UserLogin()

        {

            ReturnJson msg = new ReturnJson();

            //获取页面传递的数据

            string strUserNuber = Request["UserNuber"].Trim();//用户名

            string strPassword = Request["password"].Trim();//密码

            string strValidCode = Request["validCode"].Trim();//验证码

            string strIsRember = Request["rememberMe"].Trim();//记住否       

            string strUserTypeClass = Request["UserTypeClass"];//用户类型ID

             //获取存放在session中的验证码

            string sessionValiCode = "";

            try

            {

                sessionValiCode = Session["validCode"].ToString();

            }

            catch (Exception e)

            {

                msg.Text = "验证码丢失!请刷新验证码,重新登录验证";

                return Json(msg, JsonRequestBehavior.AllowGet);

            }

//判断填入的验证和session中的验证码是否一致

            if (sessionValiCode.Equals(strValidCode.Trim(), StringComparison.InvariantCultureIgnoreCase))

            {

                try

                {

                    PW_User dbUser = (from tbUser in myModel.PW_User

                                      where tbUser.UserNuber == strUserNuber && tbUser.ToVoidNo == true

                                      select tbUser).Single();//单条数据据,当没有数据或者有多条数据时会触发异常

                    ///将用户输入的密码进行AES265后与数据库中的密码对比

                    string password = AESEncryptHelper.Encrypt(strPassword);

                    if (dbUser.Password.Equals(password))

                    {

                        var listUserType = (from tbUser in myModel.PW_User

                                            join tbUserRoleDetail in myModel.PW_UserRoleDetail on tbUser.UserID equals tbUserRoleDetail.UserID

                                            join tbUserType in myModel.SYS_UserType on tbUserRoleDetail.UserTypeID equals tbUserType.UserTypeID

                                            where tbUser.UserID == dbUser.UserID && tbUserType.typeClass == strUserTypeClass

                                            select new

                                            {

                                                tbUserType.UserTypeID,

                                                tbUserType.UserType

                                            }).ToList();



                        if (listUserType.Count > 0)

                        {

                            //用户身份验证完成 开始处理登录信息

                            //获取用户类型名称

                            Session["UserID"] = dbUser.UserID; // 传递 UserID  

                            Session["UserTypeID"] = listUserType[0].UserTypeID;// 传递 UserTypeID 

                            Session["ServerTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ;//登录时间

                            Session["UserTypeClass"] = strUserTypeClass;//用户的类型 1-学生;2-教师;3-管理

                                                                        //如果需要记住密码 strIsRember =="true "设置cookie

                            if (strIsRember == "true")

                            {

                                //记住密码 保存cookie

                                HttpCookie cookie = new HttpCookie("user");

                                cookie.Expires = DateTime.Now.AddDays(7);//保存7天

                                //HttpUtility 提供在处理 Web 请求时用于编码和解码 URL 的方法

                                //UrlEncode()使用指定的编码对象,对 URL 字符串进行编码

                                cookie["UserNuber"] = HttpUtility.UrlEncode(strUserNuber, Encoding.GetEncoding("UTF-8"));//用户名

                                cookie["Password"] = strPassword;//密码

                                cookie["UserTypeClass"] = strUserTypeClass;//用户类型

                                Response.Cookies.Add(cookie);

                            }

                            else {

                                //删除 cookie

                                HttpCookie cookie = new HttpCookie("user");

                                cookie.Expires = DateTime.Now.AddDays(-1);//通过设置 Cookie 的过期时间为负,强制使 Cookie 过期

                                Response.Cookies.Add(cookie);

                            }

                            msg.State = true;

                            msg.Text = "用户登录成功";

                        }

                        else

                        {

                            msg.Text = "用户类型错误!";

                        }

                    }

                    else {

                        msg.Text = "用户密码错误,请重新输入";

                    }

                }

                catch (Exception e)

                {

                    Console.WriteLine(e);

                    msg.Text = "此用户不存在,请重新输入";

                  

                }

            }

            else {

                msg.Text = "验证码错误!请重新登录验证";

            }

                return Json(msg, JsonRequestBehavior.AllowGet);

       

        }

5.模块权限查询 By 用户ID

       

public ActionResult SelectModularJurisdiction()

        {

            if (Session["UserID"] != null)

            {

                int userId = Convert.ToInt32(Session["UserID"]);

                //读取权限信息

                var tempModulars = from tbUserRoleDetail in myModel.PW_UserRoleDetail

                                   join tbJurisdiction in myModel.PW_Jurisdiction on tbUserRoleDetail.UserTypeID equals tbJurisdiction.UserTypeID

                                   join tbModularDetail in myModel.SYS_ModularDetail on tbJurisdiction.ModularDetailID equals tbModularDetail.ModularDetailID

                                   join tbModular in myModel.SYS_Modular on tbModularDetail.ModularID equals tbModular.ModularID

                                   where tbUserRoleDetail.UserID == userId

                                   select new

                                   {

                                       ID = tbModularDetail.ModularID,

                                       Name = tbModular.ModularName.Trim()

                                    };

                //外连接(左连接)

                var userModulars = (from tbSysModular in myModel.SYS_Modular

                                    join tbTempModulars in tempModulars on tbSysModular.ModularID equals tbTempModulars.ID into temp

                                    select new

                                    {

                                        ModularID = tbSysModular.ModularID,

                                        ModularName = tbSysModular.ModularName.Trim(),

                                        ID = temp.Select(t => t.ID).FirstOrDefault() != null ? temp.Select(t => t.ID).FirstOrDefault() : 0

                                    }).ToList();

                return Json(userModulars, JsonRequestBehavior.AllowGet);

            }

            else {

                return Json("", JsonRequestBehavior.AllowGet);

            }

        }

6.数据回填

public ActionResult Login()

        {

            #region 读取cookie中的数据 登录页面数据回填

            string UserNuber = "";

            string Password = "";

            string UserTypeClass = "";

            bool isRember = false;

            //读取浏览器请求传递的cookie

            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies["user"];

            if (cookie != null)//判断cookie是否存在

            {

                if (cookie["UserNuber"] != null)

                {

                    //UserNuber = System.Web.HttpContext.Current.Server.UrlDecode(cookie["UserNuber"]);

                    UserNuber = HttpUtility.UrlDecode(cookie["UserNuber"], Encoding.GetEncoding("UTF-8"));

                }

                if (cookie["Password"] != null)

                {

                    Password = System.Web.HttpContext.Current.Server.UrlDecode(cookie["Password"]);

                }

                if (cookie["UserTypeClass"] != null)

                {

                    UserTypeClass = System.Web.HttpContext.Current.Server.UrlDecode(cookie["UserTypeClass"]);

                }

                isRember = true;

            }

            #endregion

            ViewBag.UserNuber = UserNuber;

            ViewBag.Password = Password;

            ViewBag.UserTypeClass = UserTypeClass;

            ViewBag.isRember = isRember;

            return View();

你可能感兴趣的:(C#,笔记,MVC,html,javascript,c#)