Asp.Net MVC 5使用Identity之簡單的註冊和登陸
由於.Net MVC 5登陸和註冊方式有很多種,但是Identity方式去實現或許會更簡單更容易理解
首先新建一個項目
其次如下選擇Empty和MVC的選項
然後打開NuGet包管理器分別安裝幾個包
- EntityFramework
- Microsoft.AspNet.Identity.Core
- Microsoft.AspNet.Identity.EntityFramework
- Microsoft.AspNet.Identity.Owin
- Modernizr
- Microsoft.Owin.Host.SystemWeb
- Bootstrap
然後往Models文件夾裏面添加ApplicationUser類,SignInModel類,SignUpModel類,ApplicationDbContext類,當然ApplicationDbContext類你也可以分到DbContext到另一個類庫,我這是做演示用的,分層不用麽這麽明確
----------------------------------------------------------------------
ApplicationUser類
ApplicationDbContext類
SignInModel類
SignUpModel類
然後往App_Start文件夾裏面添加ApplicationSignInManager類,ApplicationUserManager類,ApplicationUserStore類
---------------------------------------------------------------------
ApplicationUserManager類
ApplicationSignInManager類
ApplicationUserStore類
然後往Controller文件夾裏面添加HomeController控制器,AccountController控制器
先往HomeController控制器裏添加index視圖
index視圖代碼
@using Microsoft.AspNet.Identity @{ ViewBag.Title = "Index"; } <h2>Index</h2> @if (Request.IsAuthenticated) {using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) { @Html.AntiForgeryToken() <p>Hello @User.Identity.GetUserName()</p> <ul> <li><a href="javascript:document.getElementById(‘logoutForm‘).submit()">Log off</a></li> </ul> } } else { <ul> <li> @Html.ActionLink("Login", "Login", "Account") </li> <li> @Html.ActionLink("Register", "Register", "Account") </li> </ul> }
然後AccountController控制器代碼
private ApplicationSignInManager signInManager; private ApplicationUserManager userManager; public ApplicationSignInManager SignInManager { get { return signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { signInManager = value; } } public ApplicationUserManager UserManager { get { return userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { userManager = value; } } [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(SignInModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.Failure: default: ModelState.AddModelError("", "登陸無效"); return View(model); } } [AllowAnonymous] public ActionResult Register() { return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(SignUpModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToAction("Index", "Home"); } AddErrors(result); } return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { AuthenticationManager.SignOut(); return RedirectToAction("Index", "Home"); } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } return RedirectToAction("Index", "Home"); } private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } }
然後分別添加生成Login和Register頁面
Login頁面代碼
@model IdentityDemo.Models.SignInModel @{ ViewBag.Title = "Login"; } <h2>Login</h2> @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>SignInModel</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.RememberMe, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <div class="checkbox"> @Html.CheckBoxFor(model => model.RememberMe) @Html.ValidationMessageFor(model => model.RememberMe, "", new { @class = "text-danger" }) </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="SignIn" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("註冊", "Register") </div>
Register頁面代碼
@model IdentityDemo.Models.SignUpModel @{ ViewBag.Title = "Register"; } <h2>Register</h2> @using (Html.BeginForm("Register", "Account", FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>SignUpModel</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.PasswordFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="SignUp" class="btn btn-default" /> </div> </div> </div> }
然後往項目的根目錄添加Startup類
然後修改根目錄的Web.Config文件
最後我們來測試一下看看效果怎麽樣,如下圖
Asp.Net MVC 5使用Identity之簡單的註冊和登陸