MVC5----用戶登陸及驗證碼


隨便寫寫記錄一下學習的過程

登陸

Models中添加添加

public class LoginViewModel
    {
        [Required(ErrorMessage = "*")]
        [Display(Name = "機構號")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "*")]
        [DataType(DataType.Password)]
        [Display(Name = "密碼")]
        public string PassWord { get; set; }

        [Required(ErrorMessage = "*")]
        [Display(Name = "驗證碼")]
        public string Codeimg { get; set; }

        public string ErrorMsg { get; set; }
    }

 

  Views代碼:

其中ErrorMsg我是為了顯示錯誤信息的,其他好的方法還不知道。。。

 @using (Html.BeginForm("Login", "Admin", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)
            <div class="login_mid_right">
                <div class="login_mid_right_ul">
                    <div class="form-group">
                        @Html.LabelFor(m => m.UserName, new { @class = "col-md-3 control-label" })
                        <div class="col-md-8">
                            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
                        </div>@Html.ValidationMessageFor(m => m.UserName)
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(m => m.PassWord, new { @class = "col-md-3 control-label" })
                        <div class="col-md-8">
                            @Html.PasswordFor(m => m.PassWord, new { @class = "form-control" })
                        </div> @Html.ValidationMessageFor(m => m.PassWord)
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(m => m.Codeimg, new { @class = "col-md-3 control-label" })
                        <div class="col-md-4">
                            @Html.TextBoxFor(m => m.Codeimg, new { @class = "form-control" })
                            
                        </div> @Html.ValidationMessageFor(m => m.Codeimg)
                        &nbsp;&nbsp;
                        <img class="codeimg" title="看不清,點擊刷新" alt="看不清,點擊刷新" src="/Extensions/Codeimg.ashx" onclick="javascript:this.src=this.src+'?rnd=' + Math.random();" />
                    </div>
                    <div class="form-group">
                        <div class="col-md-offset-3 col-md-9">
                            <input type="submit" value="登 錄" class="btn-lg btn-default" />
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-offset-3 col-md-9">
                            @Html.ValidationMessageFor(m => m.ErrorMsg)
                        </div>
                    </div>
                </div>
            </div>
        }

 

  登陸的驗證,在對應的Controllers中:

public class AdminController : Controller
    {
        private SimonDBContext db = new SimonDBContext();
        //
        // GET: /Admin/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }

        public ActionResult LoginOut()
        {
            Session.Clear();
            Session.Abandon();
            return RedirectToAction("Login", "Admin");
        }

        [HttpPost]
        public ActionResult Login([Bind(Include = "UserName,PassWord,Codeimg")] LoginViewModel login, string returnUrl)
        {
            //return View();
            if (ModelState.IsValid)
            {
                int i = 9;
                if (Session["checkCode"].ToString() != login.Codeimg.ToUpper())
                {
                    ModelState.AddModelError("ErrorMsg", "驗證碼不正確!");
                }
                else
                {
                    i = Authentication(login.UserName, Common.Helper.Encryption.SHA256(login.PassWord));
                }
                if (i == 0)
                {
                    //Cookie
                    //HttpCookie cookie = new HttpCookie("User");
                    //cookie.Values.Add("UserName", login.UserName);
                    //Response.Cookies.Add(cookie);
                    //Session
                    Session["userName"] = login.UserName;
                    return RedirectToAction("Index", "Admin");
                }
                else if (i == 1)
                {
                    ModelState.AddModelError("ErrorMsg", "該用戶已被禁用!");
                }
                else
                {
                    ModelState.AddModelError("ErrorMsg", "密碼或用戶名錯誤!");
                }
            }
            return View("Login");
        }
        /// <summary>
        /// 登陸驗證
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pass"></param>
        /// <returns>
        /// 0:登錄成功
        /// 1:該用戶已被禁用
        /// 9:密碼或用戶名錯誤
        /// </returns>
        public int Authentication(string userName, string pass)
        {
            int res = 0;
            AdminManager am = db.AdminManager.SingleOrDefault(c => c.UserName == userName);
            if (am == null)
            {
                return 9;
            }
            if (am.Flag != "1")
            {
                return 1;
            }
            if (am.PassWord != pass)
            {
                return 9;
            }
            return res;
        }
    }

 做好了登陸,在其他頁面就需要添加驗證是否登陸,添加UserAuthorizeAttribute

public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            if (HttpContext.Current.Session["userName"] == null)
            {
               
                return false;
            }
            return true;
        }
    }

在需要驗證的Controller上添加 [UserAuthorize]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM