查看: 722|回复: 0

[.NET开发] Asp.Net MVC 5使用Identity之简单的注册和登陆

发表于 2017-9-26 08:00:01
尚学堂AD

由于.Net MVC 5登陆和注册方式有很多种,但是Identity方式去实现或许会更简单更容易理解

首先新建一个项目

其次如下选择Empty和MVC的选项

然后打开NuGet包管理器分别安装几个包

  1. EntityFramework
  2. Microsoft.AspNet.Identity.Core
  3. Microsoft.AspNet.Identity.EntityFramework
  4. Microsoft.AspNet.Identity.Owin
  5. Modernizr
  6. Microsoft.Owin.Host.SystemWeb
  7. 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视图代码

  1. @using Microsoft.AspNet.Identity
  2. @{
  3. ViewBag.Title = "Index";
  4. }
  5. <h2>Index</h2>
  6. @if (Request.IsAuthenticated)
  7. {
  8. using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
  9. {
  10. @Html.AntiForgeryToken()
  11. <p>Hello @User.Identity.GetUserName()</p>
  12. <ul>
  13. <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
  14. </ul>
  15. }
  16. }
  17. else
  18. {
  19. <ul>
  20. <li>
  21. @Html.ActionLink("Login", "Login", "Account")
  22. </li>
  23. <li>
  24. @Html.ActionLink("Register", "Register", "Account")
  25. </li>
  26. </ul>
  27. }
复制代码

然后AccountController控制器代码

  1. private ApplicationSignInManager signInManager;
  2. private ApplicationUserManager userManager;
  3. public ApplicationSignInManager SignInManager
  4. {
  5. get
  6. {
  7. return signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
  8. }
  9. private set
  10. {
  11. signInManager = value;
  12. }
  13. }
  14. public ApplicationUserManager UserManager
  15. {
  16. get { return userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
  17. private set
  18. {
  19. userManager = value;
  20. }
  21. }
  22. [AllowAnonymous]
  23. public ActionResult Login(string returnUrl)
  24. {
  25. ViewBag.ReturnUrl = returnUrl;
  26. return View();
  27. }
  28. [HttpPost]
  29. [AllowAnonymous]
  30. [ValidateAntiForgeryToken]
  31. public async Task<ActionResult> Login(SignInModel model, string returnUrl)
  32. {
  33. if (!ModelState.IsValid)
  34. {
  35. return View(model);
  36. }
  37. var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
  38. switch (result)
  39. {
  40. case SignInStatus.Success:
  41. return RedirectToLocal(returnUrl);
  42. case SignInStatus.Failure:
  43. default:
  44. ModelState.AddModelError("", "登陆无效");
  45. return View(model);
  46. }
  47. }
  48. [AllowAnonymous]
  49. public ActionResult Register()
  50. {
  51. return View();
  52. }
  53. [HttpPost]
  54. [AllowAnonymous]
  55. [ValidateAntiForgeryToken]
  56. public async Task<ActionResult> Register(SignUpModel model)
  57. {
  58. if (ModelState.IsValid)
  59. {
  60. var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  61. var result = await UserManager.CreateAsync(user, model.Password);
  62. if (result.Succeeded)
  63. {
  64. await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
  65. return RedirectToAction("Index", "Home");
  66. }
  67. AddErrors(result);
  68. }
  69. return View(model);
  70. }
  71. [HttpPost]
  72. [ValidateAntiForgeryToken]
  73. public ActionResult LogOff()
  74. {
  75. AuthenticationManager.SignOut();
  76. return RedirectToAction("Index", "Home");
  77. }
  78. private void AddErrors(IdentityResult result)
  79. {
  80. foreach (var error in result.Errors)
  81. {
  82. ModelState.AddModelError("", error);
  83. }
  84. }
  85. private ActionResult RedirectToLocal(string returnUrl)
  86. {
  87. if (Url.IsLocalUrl(returnUrl))
  88. {
  89. return Redirect(returnUrl);
  90. }
  91. return RedirectToAction("Index", "Home");
  92. }
  93. private IAuthenticationManager AuthenticationManager
  94. {
  95. get { return HttpContext.GetOwinContext().Authentication; }
  96. }
复制代码

然后分别添加生成Login和Register页面

Login页面代码

  1. @model IdentityDemo.Models.SignInModel
  2. @{
  3. ViewBag.Title = "Login";
  4. }
  5. <h2>Login</h2>
  6. @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post))
  7. {
  8. @Html.AntiForgeryToken()
  9. <div class="form-horizontal">
  10. <h4>SignInModel</h4>
  11. <hr />
  12. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  13. <div class="form-group">
  14. @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
  15. <div class="col-md-10">
  16. @Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
  17. @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
  18. </div>
  19. </div>
  20. <div class="form-group">
  21. @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
  22. <div class="col-md-10">
  23. @Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
  24. @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
  25. </div>
  26. </div>
  27. <div class="form-group">
  28. @Html.LabelFor(model => model.RememberMe, htmlAttributes: new { @class = "control-label col-md-2" })
  29. <div class="col-md-10">
  30. <div class="checkbox">
  31. @Html.CheckBoxFor(model => model.RememberMe)
  32. @Html.ValidationMessageFor(model => model.RememberMe, "", new { @class = "text-danger" })
  33. </div>
  34. </div>
  35. </div>
  36. <div class="form-group">
  37. <div class="col-md-offset-2 col-md-10">
  38. <input type="submit" value="SignIn" class="btn btn-default" />
  39. </div>
  40. </div>
  41. </div>
  42. }
  43. <div>
  44. @Html.ActionLink("注册", "Register")
  45. </div>
复制代码

Register页面代码

  1. @model IdentityDemo.Models.SignUpModel
  2. @{
  3. ViewBag.Title = "Register";
  4. }
  5. <h2>Register</h2>
  6. @using (Html.BeginForm("Register", "Account", FormMethod.Post))
  7. {
  8. @Html.AntiForgeryToken()
  9. <div class="form-horizontal">
  10. <h4>SignUpModel</h4>
  11. <hr />
  12. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  13. <div class="form-group">
  14. @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
  15. <div class="col-md-10">
  16. @Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
  17. </div>
  18. </div>
  19. <div class="form-group">
  20. @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
  21. <div class="col-md-10">
  22. @Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
  23. </div>
  24. </div>
  25. <div class="form-group">
  26. @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
  27. <div class="col-md-10">
  28. @Html.PasswordFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
  29. </div>
  30. </div>
  31. <div class="form-group">
  32. <div class="col-md-offset-2 col-md-10">
  33. <input type="submit" value="SignUp" class="btn btn-default" />
  34. </div>
  35. </div>
  36. </div>
  37. }
复制代码

然后往项目的根目录添加Startup类

然后修改根目录的Web.Config文件

最后我们来测试一下看看效果怎么样,如下图



回复

使用道具 举报