.NetCore Idetity(一) ------Identity服务的配置

.NetCore Idetity(一) ------Identity服务的配置

前景回顾:
https://blog.csdn.net/wsnbbdbbdbbdbb/article/details/117232416?spm=1001.2014.3001.5501

添加ASP.NET Core Identity服务

一 、设置上下文

(需要的包)Microsoft.AspNetCore.Identity.EntityFrameworkCore

1 将StudentDbContext继承改为IdentityDbContext(IdentityDbContext继承与DbContext)

2.在Startup.cs文件中,ConfigureServices注册服务
    services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<StudentDbContext>();

3.在Configure中应用中间件

/注意顺序不能乱,必须在Routing之前,因为身份验证需要在进入mvc终端前就要进行
  app.UseAuthentication();
  app.UseRouting();

4.在StudentDbContext中重写OnModelCreating()

方法

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Student.Models
{
    public class StudentDbContext:IdentityDbContext
    {
        public StudentDbContext(DbContextOptions<StudentDbContext>options):base(options)
        {

        }

        public DbSet<Student> Student { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        //这里是添加种子文件
            modelBuilder.Seed();
            //因为已经重写了OnModelCreating,但Identity还需要调用基类的OnModelCreating(),所以需要使用base进行基类调用
            base.OnModelCreating(modelBuilder);
        }
    }
}
//base用法详见 https://blog.csdn.net/cplvfx/article/details/82982862

二、进行数据库的迁移

1.Add-Migration Identity

2.Update-Database

三、 迁移效果展示

在这里插入图片描述

posted @ 2021-05-28 19:18  有诗亦有远方  阅读(23)  评论(0)    收藏  举报  来源