我目前正在尝试将Identity的UserManager
类连接到一个简单的应用程序。尝试这样做时,.FindByEmailAsync
以及尝试查找用户的任何其他方法总是向我返回空用户。 UserManager
本身不为null,但似乎无法正确找到我的任何用户。我的应用程序中的所有内容都使用相同的数据库,并且我已验证用户是否存在于数据库中。
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private SignInManager<ApplicationUser> _signInManager;
private UserManager<ApplicationUser> _userManager;
public UsersController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public async Task<ActionResult<ApplicationUser>> Get()
{
//this returns null
var user = await _userManager.FindByEmailAsync("admin@admin.com");
//this works
using (var db = new ApplicationDbContext(GetDbOptions()))
{
return db.Users.Single(x => x.Email == "admin@admin.com")
}
}
}
我的Startup.cs
类如下:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentityCore<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
//.AddSignInManager<SignInManager<ApplicationUser>>() tried adding these with no success- same behavior
//.AddUserManager<UserManager<ApplicationUser>>();
正在将用户植入数据库,如下所示:
private static void SeedIdentityUsers(IServiceScope serviceScope)
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var PasswordHash = new PasswordHasher<ApplicationUser>();
if (!context.Users.Any(u => u.UserName == "admin@admin.com"))
{
var user = new ApplicationUser
{
UserName = "admin@admin.com",
Email = "admin@admin.com",
};
user.PasswordHash = PasswordHash.HashPassword(user, "somepassword");
context.Users.Add(user);
context.SaveChanges();
}
}