在实际使用时会发现很多字段在IdentityUser中并不存在,比如增加生日,地址等字段,可在模型类中实现自己的模型并继承自IdentityUser,需要修改的代码为以下类
一、新增模型
using System; using Microsoft.AspNetCore.Identity; namespace Shop.Models { public class MyUser:IdentityUser { public string IdCard { get; set; } public DateTime Birthday { get; set; } } }
二、修改Startup.cs
修改前 services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); 修改后 services.AddDefaultIdentity<MyUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>();
三、修改ApplicationDbContext.cs
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace Shop.Models { public class ApplicationDbContext:IdentityDbContext<MyUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Region> Region { get; set; } } }
四、更新扩展字段到数据库
PM> Add-Migration addExtUser
PM> Update-Database
五、修改实现代码,以创建用户为例,红色字体为继承自IdentityUser的类库
[HttpPost] public async Task<IActionResult> Register(CreateUserViewModel input) { if (ModelState.IsValid) { var user = new MyUser() { Id = input.id, UserName = input.UserName, Email = input.Email, PhoneNumber = input.PhoneNumber, Birthday = input.Birthday }; //创建用户 var result = await _userManager.CreateAsync(user,input.PasswordHash); //如果成功则返回用户列表 if (result.Succeeded) { return RedirectToAction("Index"); } } return View(input); }
可看到Birthday已经可以使用,视图记得@model引用也修改下才能展示,如下代码
@model IEnumerable<MyUser>
@inject SignInManager<MyUser> SignInManager