示例
1、将RegisterDTO.cs中的Name字段改为PersonName,相应的Register.cshtml视图中也要更新;
2、AccountController.cs更新为如下
using ContactsManager.Core.Domain.IdentityEntities;
using ContactsManager.Core.DTO;
using CRUDExample.Controllers;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace ContactsManager.UI.Controllers
{
[Route("[controller]/[action]")]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
public AccountController(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Register(RegisterDTO registerDTO)
{
//Check for validation errors
if (ModelState.IsValid == false)
{
ViewBag.Errors = ModelState.Values.SelectMany(temp => temp.Errors).Select(temp => temp.ErrorMessage);
return View(registerDTO);
}
//TO DO: Store user registration details into Identity database
ApplicationUser applicationUser = new ApplicationUser()
{
PersonName = registerDTO.PersonName,
Email = registerDTO.Email,
PhoneNumber = registerDTO.Phone,
UserName = registerDTO.Email
};
IdentityResult result = await _userManager.CreateAsync(applicationUser,registerDTO.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(PersonsController.Index), "Persons");
}
else
{
foreach (IdentityError error in result.Errors)
{
ModelState.AddModelError("Register",error.Description);
}
return View(registerDTO);
}
}
}
}
3、运行程序点击Register填写字段后,点击Register出现如下报错
说明在更换DbContext更换为IdentityDbContext后没有执行更新数据库的命令
4、执行Add-Migration Idenity和Update-DataBase命令
运行程序注册后,数据表中AspNetUsers可以看到注册的用户。
Gitee获取源码:
https://gitee.com/huang_jianhua0101/asp.-net-core-8.git
标签:Register,userManager,roleManager,284,public,Manager,User,using,registerDTO From: https://blog.csdn.net/KevinHuang2088/article/details/139688330