【问题标题】:How to implement .NET Core Identity with a custom WebAPI如何使用自定义 WebAPI 实现 .NET Core Identity
【发布时间】:2020-05-01 18:05:04
【问题描述】:

我有一个疯狂的时刻(阅读:“一周”)。我不知道如何在我的网络项目中实施 .Net Core Identity。

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

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

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

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

【问题讨论】:

    标签: asp.net-core razor asp.net-core-webapi identity


    【解决方案1】:

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

    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;    
    
    public class MyContext : IdentityDbContext<ApplicationUser, ApplicationRole, int, ApplicationUserClaim, ApplicationUserRole, ApplicationUserLogin, ApplicationRoleClaim, ApplicationUserToken>
            {
                public MyContext (DbContextOptions<MyContext > options)
                    : base(options)
                {
    
                }
        }
    

    【讨论】:

    • 您好,感谢您的帮助。但是我真的不明白对上下文的更改会有什么帮助?我不希望 Web 项目与数据库有任何连接....
    【解决方案2】:

    这个解决方案对我有用:

    我添加了一个新的 UserStore。 创建新类: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>();
    
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多