1-创建RegisterViewModel类

namespace MvcCookieAuthSample.ViewModel
{
public class RegisterViewModel
{ [Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; } [Required]
[DataType(DataType.Password)]
public string Password { get; set; } [Required]
[DataType(DataType.Password)]
public string ConfirmPassword { get; set; }
}
}

2-创建一个Register.cshtml前端页面

asp-validation-for用于验证,如果加了 Html.PartialAsync("_ValidationScriptsPartial")则会启用客户端验证
<h3>Register</h3>
@model MvcCookieAuthSample.ViewModel.RegisterViewModel
<div class="row">
<div class="col-md-4">
<form method="post">
<h4>register a new account</h4>
<div asp-validation-summary="All" class="text-danger"></div>
<hr /> <div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div> <div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div> <div class="form-group">
<label asp-for="ConfirmPassword"></label>
<input asp-for="ConfirmPassword" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div> <button type="submit" class="btn btn-default">Register</button>
</form>
</div>
</div> @section Scripts{
@await Html.PartialAsync("_ValidationScriptsPartial") @*用于客户端验证*@
}

3-在后端页面处理前端提交的请求

   [HttpPost]
public async Task<IActionResult> Register(ViewModel.RegisterViewModel registerViewModel)
{
if (ModelState.IsValid)
{
Models.ApplicationUser applicationUser = new Models.ApplicationUser()
{
Email = registerViewModel.Email,
UserName = registerViewModel.Email,
NormalizedEmail = registerViewModel.Email
}; IdentityResult result = await _userManager.CreateAsync(applicationUser, registerViewModel.Password);//注册
if (result.Succeeded)
{
await _signInManager.SignInAsync(applicationUser, true);//登陆
return RedirectToAction("Index", "Home");
}
else
{
foreach(var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description); //增加错误信息
}
}
}
return View();
}
05-15 07:54