如何在网络核心的Web API

问题描述:

嗨扩展身份我使用的EntityFramework核心,并希望使用内置的身份认证与网络核心网络API,所以为什么我所做的就是以下几点:如何在网络核心的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继承:

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); 
     } 
} 

然后我注册了我的自定义类的d在Startup.cs我的数据库环境(在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 Createad

数据库的所有标识表格加上自定义的表格已成功创建。

找我发现使用Asp.Net网络API一个身份的版本在互联网上,似乎我需要在我的自定义用户类覆盖的方法,所以我的类的属性将被保存。

我跟着这个教程中的Web API来实现身份,大部分教程使用Identity与MVC不是纯Web API:Tutorial I followed

我的问题是:

如何创建一个控制器一个POST动作,所以我可以注册 用户。我需要在自定义用户类中修改什么,以便我可以将自定义属性保存在Db中。

此外,当我登记我的用户它从我的 类具有的属性:名字,姓氏和生日。我的意思是他们不能 为空,他们需要填补,如果他们是空的,那么你不能 它保存到数据库。

感谢

+0

本教程介绍了如何创建[AaccountController](http://www.an drewhoefling.com/dotnet/core/2017/04/18/dotnet-core-web-api-identity-token-authentication.html#build-the-api)。你在哪里被卡住了? – Win

+0

@win本教程是伟大的,但我想我的自定义用户表,所以这就是为什么我从IdentityUser扩展添加自定义字段,我不知道如何保存我的自定义字段 –

有在their GitHub的仓库看看样品:

例如,对于在控制器你的帖子,你可以看一下注册方法(你真的找方法为是的UserManager对象的CreateAsync法)

https://github.com/aspnet/Identity/blob/dev/samples/IdentitySample.Mvc/Controllers/AccountController.cs