MVC 5----ユーザー登録及び認証コード

21060 ワード

勝手に勉強の過程を書き記す
上陸する
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]を追加