ASP.NET Identity教程二:(用户管理6)修改用户密码
一,在ViewModels下新建模型ChangePasswordViewModel
using System.ComponentModel.DataAnnotations; namespace jsdhh2.ViewModels { public class ChangePasswordViewModel { [Required] [DataType(DataType.Password)] [Display(Name = "当前密码")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "新密码")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "确认新密码")] [Compare("NewPassword", ErrorMessage = "新密码和确认密码不匹配。")] public string ConfirmPassword { get; set; } } }
二、在UserController中新建两个方法
// // // GET: /Manage/ChangePassword public ActionResult ChangePassword() { return View(); } // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> ChangePassword(jsdhh2.ViewModels.ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Login", "User"); } AddErrors(result); return View(model); }
5.新建一个ChangePassword视图
@model jsdhh2.ViewModels.ChangePasswordViewModel @{ ViewBag.Title = "更改密码"; } <h2>@ViewBag.Title。</h2> @using (Html.BeginForm("ChangePassword", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() <h4>更改密码表单</h4> <hr /> @Html.ValidationSummary("", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(m => m.OldPassword, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.PasswordFor(m => m.OldPassword, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.NewPassword, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.PasswordFor(m => m.NewPassword, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="更改密码" class="btn btn-default" /> </div> </div> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
运行情况