我正在尝试在我的应用程序中实现基本身份验证。用户应存储在postgresql数据库中。
我能够创建一个用户,但我不知道它存储在哪里。它不存储在我的数据库中。但是所有创建的用户都可以从UserManager
存储和访问。重新启动后,创建的用户仍然在那里。所以它不存储在我的数据库或内存中。
我使用这部分来实现与实体框架的身份。
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<DatabaseContext>()
.AddDefaultTokenProviders();
User
和Role
类只是从IdentityUser
和IdentityRole
延伸,Guid
作为关键类型。
我使用npgsql
作为数据库。我很确定它正在运行,因为迁移正确迁移:
var connectionString = Configuration.GetConnectionString("DatabaseContext");
services.AddEntityFrameworkNpgsql()
.AddDbContext<DatabaseContext>(options => options.UseNpgsql(connectionString));
为了创建和获取用户,我在控制器中注入Microsoft.AspNetCore.Identity.UserManager<User>
。
为什么用户没有存储在我的数据库中?
UserManager<TUser>
将寻找注射的IUserStore<TUser>
。这就是它如何持续存在用户并与您的数据库聊天。用户存储的默认实现can be found here.默认情况下,此实现看起来直接注入DbContext
。
我尝试的事情:
IdentityDbContext
IUserStore
并查看Context
属性以查看它正在使用的数据库上下文。如果您完全确定您的用户没有进入您的数据库,那么IUserStore<TUser>
必须使用与您正在使用的用户不同的上下文。如果是这种情况,请删除其他上下文或将更具体的IUserStore
版本添加到您的服务集合中。例如:用IUserStore<TUser>
替换服务中的UserStore<TUser, IdentityRole, DatabaseContext, string>
。 (注意我们在那里指定DatabaseContext
,而不是基类DbContext
)