参考:Docs ASP.NET Core 身份验证
ASP.NET Core Identity 是一个用户管理系统
- 它是一个完善的、全面的、庞大的框架
- 创建、查询、更改、删除 账户信息
- 验证和授权
- 密码重置
- 双重身份认证
- 支持扩展登录,如微软、Facebook、QQ 等
- 它提供了一个丰富的 API,并且这些 API 还可以进行大量的扩展
添加 Identity 的步骤
让 DbContext 类继承 IdentityDbContext 类:
public class AppDbContext : IdentityDbContext{public AppDbContext(DbContextOptions options) : base(options){}...}
添加 Identity 服务:
public void ConfigureServices(IServiceCollection services){services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("StudentDBConnection")));// 1.添加 Identity 服务 2.使用 AppDbContext 存储与身份认证相关的数据services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<AppDbContext>();...}
添加中间件:
public void Configure(IApplicationBuilder app, IHostingEnvironment env){...app.UseStaticFiles();// 注意要放在 UseMvc 之前app.UseAuthentication();app.UseMvc(routes =>{routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");});}
因为 Identity 重写过 OnModelCreating,所以需要保证 Add-Migration 时它能被调用到,于是得修改我们的 OnModelCreating
protected override void OnModelCreating(ModelBuilder modelBuilder){base.OnModelCreating(modelBuilder);modelBuilder.Seed();}
生成 ASP.NET Core Identity 表
- Add-Migration
- Update-Database
查看生成好的表

