用户注册主要有2个方法,1、密码加密 2、用户注册 3、ASP.NET Core Identity 使用密码策略、锁定和 cookie 配置等设置的默认值。 可以在类中重写这些设置 Startup(官方详情点这里)
首先创建CreateUserViewModel视图模型
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Shop.ViewModel { public class CreateUserViewModel { [Required(ErrorMessage = "用户名不能为空")] [DisplayName("用户名")] public string UserName { get; set; } [EmailAddress(ErrorMessage = "邮箱格式不正确")] [DisplayName("邮箱")] public string Email { get; set; } [DisplayName("手机号")] [MinLength(11,ErrorMessage = "手机位数不足11位"), StringLength(11)] public string PhoneNumber { get; set; } [Required(ErrorMessage = "密码不能为空")] [DataType(DataType.Password)] [DisplayName("密码")] public string PasswordHash { get; set; } } }
创建regiseter方法
public IActionResult Register() { return View(); }
创建Register视图
@model Shop.ViewModel.CreateUserViewModel @{ ViewData["Title"] = "Register"; } <h1>Register</h1> <form class="form-horizontal" asp-action="Register" method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <fieldset> <div class="control-group"> <label class="control-label">用户名</label> <div class="controls"> <input type="text" placeholder="" class="input-xlarge" asp-for="UserName"> <span asp-validation-for="UserName" class="text-danger"></span> </div> </div> <div class="control-group"> <label class="control-label">邮箱</label> <div class="controls"> <input type="text" placeholder="" class="input-xlarge" asp-for="Email"> <span asp-validation-for="Email" class="text-danger"></span> </div> </div> <div class="control-group"> <label class="control-label">手机号</label> <div class="controls"> <input type="text" placeholder="" class="input-xlarge" asp-for="PhoneNumber"> <span asp-validation-for="PhoneNumber" class="text-danger"></span> </div> </div> <div class="control-group"> <label class="control-label">密码</label> <div class="controls"> <input type="text" placeholder="" class="input-xlarge" asp-for="PasswordHash"> <span asp-validation-for="PasswordHash" class="text-danger"></span> </div> </div> <input type="submit" class="btn btn-primary" value="注册"> </fieldset> </form> @*输入内容跟模型定义规则不符时需要验证提示加入此脚本*@ @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
创建Register post方法
[HttpPost] public async Task<IActionResult> Register(CreateUserViewModel input) { if (ModelState.IsValid) { var user = new IdentityUser { UserName = input.UserName, Email = input.Email, PhoneNumber = input.PhoneNumber, PasswordHash = input.PasswordHash }; //创建用户 var result = await _userManager.CreateAsync(user); //如果成功则返回用户列表 if (result.Succeeded) { return RedirectToAction("Index"); } } return View(input); }
效果展示,如果验证错误则有如下提示
如果成功提交则返回用户列表页,注意:未做编号自增及用户名是否重复的验证