如何使用自定义 WebAPI 实现 .NET Core Identity

How to implement .NET Core Identity with a custom WebAPI

我正在经历一个脑筋急转弯的时刻(阅读:“一周”)。我不知道如何在我的 Web 项目中实施 .Net Core Identity。

我有 WebAPI (.NET Core 3.1) 项目和 Web 项目(Razor 页面)。 WWebAPI 项目旨在进行所有的数据库通信,Web 项目应该只用于连接到WebAPI 并显示数据。

在 Web 项目中,我搭建了标识并获得了注册、登录、注销页面。但是,脚手架会创建新的 DatabaseContext 并以这种方式连接到数据库。

我想要的是实现它以连接到我的 WebAPI 并调用我的 UserController 端点。

有人能给我指出正确的方向吗?

您的数据库上下文需要继承自以下 类。

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;    

public class MyContext : IdentityDbContext<ApplicationUser, ApplicationRole, int, ApplicationUserClaim, ApplicationUserRole, ApplicationUserLogin, ApplicationRoleClaim, ApplicationUserToken>
        {
            public MyContext (DbContextOptions<MyContext > options)
                : base(options)
            {

            }
    }

这个解决方案对我有用:

我添加了一个新的 UserStore。 创建了新的 class:ApplicationUserStore 并实现了接口 IUserStore、IUserPasswordStore、IUserEmailStore。

public class ApplicationUserStore : IUserStore<IdentityUser>, IUserPasswordStore<IdentityUser>, IUserEmailStore<IdentityUser>
{}

并且在 IdentityHostingStartup.cs 中,我删除了脚手架上下文:

services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationWebContext>();

并添加了我的商店而不是它:

public class IdentityHostingStartup : IHostingStartup
{
    public void Configure(IWebHostBuilder builder)
    {

        builder.ConfigureServices((context, services) => {

            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddUserStore<ApplicationUserStore>();

        });
    }
}