c# - 如何在 Net Core Web API 中扩展身份

标签 c# asp.net-core asp.net-core-webapi asp.net-core-identity

您好,我正在使用 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 的数据库上下文类:

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 中注册了自定义类和数据库上下文(在 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

已成功创建包含所有身份表和自定义表的数据库。

在互联网上我找到了一个使用 Asp.Net Web Api 的 Identity 版本,似乎我需要重写我的自定义用户类中的一个方法,所以我的类的属性被保存了。

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

MY QUESTION IS:

How do I create a Controller with a POST action so I can register users. And what do I need to modify in my custom user class so I can save my custom properties in the Db.

Also when I register my user it has to have the properties from my class: FirstName, LastName and BirthDay. What I meant is they cannot be null , they have to be filled, if they are empty then you cannot save it to the DB.

谢谢

最佳答案

查看 their 中的示例GitHub 存储库:

例如,对于 Controller 中的 POST,您可以查看 register 方法(您真正要查找的方法是 UserManager 对象上的 CreateAsync 方法)

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

关于c# - 如何在 Net Core Web API 中扩展身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45378688/

相关文章:

c# - CSC 与 MySQL 的 C# 命令

asp.net - ASP.Net Core MVC 中的 OutputCache

c# - 关于 MVC Controller 与独立 Web API 的架构,有多少个项目?

javascript - .NET Core API 与来自 JavaScript 的 CORS

.net - 用于 .net Core 的 Amazon DynamoDb ORM

.net-core - Postman 收到 ASP.NET Core Web API 的 404 错误

c# - 使用 Parallel.for 循环的文件 I/O 问题

c# - 如何处理重复的匿名类型成员冲突?

c# - 通过句柄获取窗口的边界

c# - 错误 : C:\Program Files\dotnet\dotnet. exe 失败,返回代码:1