ASP.NET 'FindByNameAsync' returns null?
You are trying to find an user by an email address.
You should use UserManager.FindByEmailAsync
This usually happens when you create the user using some other method than CreateAsync in Microsoft.AspNetCore.Identity.UserManager. I had the same issue because I was creating the users directly through EF, not the referred method.
All FindBy methods should work properly using this approach.
I had a similar issue for the project based on ASP.NET Core 2.2. Maybe my solution will be useful for someone.
The user can change their UserName
in the UserProfile component (by default, the UserName
was the same as Email, i.e., [email protected]
). If the user changed their Username in the profile from the default [email protected]
to user1
, then they could not log in using this new UserName, only Email.
The line below always returned NULL.
var user = await _userManager.FindByNameAsync(request.UserName);
After investigating the AspCore repository, I found FindByNameAsync method. I become suspicious about NormalizeName
line. And my current model for the UserProfile
model had only UserName
property, which was mapped later using Automapper and saved to the database. So I added computed NormalizedUserName
property and also mapped it with Automapper (_mapper.Map(UserProfileModel, dbUser);
) and saved it to the database.
public string NormalizedUserName
{
get
{
return UserName.ToUpper().Normalize(); // `UserManager` UserFindByNameAsync method is using `normalizedName` = `NormalizedUserName` from Users table (for some reason UPPERCASE, maybe SQL performance), otherwise we will always get NULL
}
}
Changes mentioned above solved my issue for NULL when using the FindByNameAsync
method.