My test code is for creating a new user if there isn't existed. and it check if user is existed, using FindByEmailAsync() method. but It returns null always, so it's creating same many users.
public HomeController(
IUnitOfWork unitOfWork,
UserManager<User> userManager)
{
_unitOfWork = unitOfWork;
_userManager = userManager;
}
public async Task<IActionResult> Index()
{
var test = await _userManager.FindByEmailAsync("[email protected]");
if (test == null)
{
// Add the user
var newUser = new User
{
UserName = "mark",
Email = "[email protected]",
Created = DateTime.Now,
Updated = DateTime.Now
};
_unitOfWork.UserRepository.Insert(newUser);
_unitOfWork.Save();
// password is 'admin'
await _userManager.CreateAsync(newUser, "admin");
}
return View();
}
Here is my startup.cs
public void ConfigureServices(IServiceCollection services)
{
// add Identity
services.AddIdentity<User, IdentityRole>(config =>
{
config.User.RequireUniqueEmail = true;
config.Password.RequiredLength = 4;
config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
})
.AddEntityFrameworkStores<MyContext>();
/// ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseIdentity();
/// ...
}
Also config.User.RequireUniqueEmail = true;
is not working, because it's creating multiple users with same email address, but I don't see any an error.
What am I doing wrong? please advise me.
Internally the UserManager
is actually searching on the NormalizedEmail
column. I would look in the database and see if that is getting populated correctly or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With