首页 文章

如何在Net Core Web API中扩展Identity

提问于
浏览
2

嗨,我正在使用EntityFramework Core,并希望使用Net Core Web Api内置的身份验证,所以我为什么这样做:

  • 创建从IdentityUser扩展的类,并添加自定义属性:
public class MyUser : IdentityUser {
        public MyUser(string username) : base (username) { }
        public string FirstName { set; get; }
        public string LastName { set; get; }
        public DateTime BirthDate { set; get; }
}

创建继承自IdentityDbContext的db上下文类:

public class DBContext : IdentityDbContext<MyUser> {
        public DBContext (DbContextOptions<DBContext> options) : base (options) { }
        public DbSet<Story> Stories { set; get; }
        protected override void OnModelCreating (ModelBuilder builder) {
            base.OnModelCreating (builder);
        }
}

然后我在Startup.cs中注册了我的自定义类和我的db上下文(在ConfigureServices方法中):

public void ConfigureServices (IServiceCollection services) {
            var connection = @"Server=(localdb)\mssqllocaldb;Database=DBEF;Trusted_Connection=True;";

            services.AddDbContext<DBContext> (options => options.UseSqlServer (connection,
                optionsBuilder => optionsBuilder.MigrationsAssembly ("WebApiEFCore")));

            services.AddIdentity<MyUser, IdentityRole> ()
                .AddEntityFrameworkStores<DBContext> ()
                .AddDefaultTokenProviders ();

            services.Configure<IdentityOptions> (o => {
                o.SignIn.RequireConfirmedEmail = true;
            });

            services.AddMvc ();
}

最后,我启用了迁移并对Db进行了更新,如下所示:
DB Createad

已成功创建包含所有标识表和自定义表的Db .

在互联网上我发现使用Asp.Net Web Api的Identity版本,我似乎需要覆盖自定义用户类中的方法,因此我的类的属性被保存 .

我按照本教程在Web Api中实现Identity,大多数教程使用Identity与MVC而不是纯Web API:Tutorial I followed

我的问题是:如何使用POST操作创建一个控制器,以便我可以注册用户 . 我需要在自定义用户类中修改哪些内容,以便将自定义属性保存在Db中 . 此外,当我注册我的用户时,它必须具有我的类的属性:FirstName,LastName和BirthDay . 我的意思是他们不能为空,他们必须填补,如果他们是空的,那么你不能将它保存到数据库 .

谢谢

1 回答

相关问题