Finding Users In ASP.NET Identity Controllers
The recent release of .NET 5 has got me looking at a lot of old code that I haven't touched for a long time, forcing me to check that code built for .NET Core 2 still works after migrations to Core 3.1 and then to .NET 5.
Amazingly, there's been very little breaking changes when it comes to the basics of Identity over the last few years.
This is a quick guide detailing how to check if a user exists, and how find the user's details using ASP.NET Identity just from their email address.
Steps and code in this guide should work in ASP.NET 5 and Core versions 2.1, 2.2, 3 & 3.1.
Check if User Exists
Here is the code for checking if a user exists, with a full explanation below.
public interface IUsers
{
public bool UserExists(string emailAddress);
}
public class Users : IUsers
{
#region Constructor
private readonly UserManager<IdentityUser> _userManager;
public Users(UserManager<IdentityUser> userMgr)
{
_userManager = userMgr;
}
#endregion
/// <summary>
/// Check if a user exists by email address
/// </summary>
/// <returns></returns>
public async bool UserExists(string emailAddress)
{
var user = await _userManager.FindByEmailAsync(emailAddress);
return user != null;
}
}
Pass the method named UserExists the email address of the user that you want to check, if the user exists then True will be returned.
Get User
The code for getting a user is almost exactly the same as checking if one exists, except we return the IdentityUser.
public interface IUsers
{
public IdentityUser GetUserByEmail(string emailAddress);
}
public class Users : IUsers
{
#region Constructor
private readonly UserManager<IdentityUser> _userManager;
public Users(UserManager<IdentityUser> userMgr)
{
_userManager = userMgr;
}
#endregion
/// <summary>
/// Check if a user exists by email address
/// </summary>
/// <returns></returns>
public async IdentityUser GetUserByEmail(string emailAddress)
{
var user = await _userManager.FindByEmailAsync(emailAddress);
return user;
}
}
Considerations
For this to work, you will need to add a reference to the new interface in your Startup.cs file.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IUsers, Users>();
}