一般情况下,ASP.NET Core应用程序使用cookie来存储用户身份验证信息。但是,如果您希望将主体数据存储在数据库中而不是cookie中,可以遵循以下步骤:
创建一个标识服务器提供程序(Identity Server Provider)来支持存储用户的主体数据。可以从NuGet安装IdentityServer4包。
Install-Package IdentityServer4
创建一个自定义用户存储库(Custom User Store)来实现实际的数据库访问逻辑。该存储库应该实现AspNetCore.Identity.IUserStore接口和AspNetCore.Identity.IUserRoleStore接口。在此示例中,使用Entity Framework Core作为数据访问框架。该存储库可能如下所示:
public class CustomUserStore : IUserStore, IUserRoleStore
{
private readonly ApplicationDbContext _dbContext;
public CustomUserStore(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task CreateAsync(ApplicationUser user, CancellationToken cancellationToken)
{
_dbContext.Users.Add(user);
await _dbContext.SaveChangesAsync(cancellationToken);
return IdentityResult.Success;
}
public async Task DeleteAsync(ApplicationUser user, CancellationToken cancellationToken)
{
_dbContext.Users.Remove(user);
await _dbContext.SaveChangesAsync(cancellationToken);
}
public async Task FindByIdAsync(string userId, CancellationToken cancellationToken)
{
return await _dbContext.Users.FindAsync(new object[] { userId }, cancellationToken);
}
public async Task FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
{
return await _dbContext.Users.FirstOrDefaultAsync(u => u.UserName == normalizedUserName, cancellationToken);
}
public Task GetNormalizedUserNameAsync(ApplicationUser user, CancellationToken cancellationToken)
{
return Task.FromResult(user.UserName);
}
public async Task GetUserIdAsync(ApplicationUser user, CancellationToken cancellationToken)
{
return (await _dbContext.Users.FirstOrDefaultAsync(u => u.Email == user