enet
enet

Reputation: 45636

How to verify if an email address exists in the AspNetUsers table in Asp.Net Core

I'm following the the sample in https://docs.asp.net/en/latest/mvc/models/validation.html?highlight=remote#remote-validation about how to use the Remote attribute:

[AcceptVerbs("Get", "Post")]
public IActionResult VerifyEmail(string email)
{
    if (!_userRepository.VerifyEmail(email))
    {
        return Json(data: $"Email {email} is already in use.");
    }

    return Json(data: true);
}

As you can see, it is suggested to create a repository with a VerifyEmail method...

I wander if I can use UserManager.FindByEmailAsync(string email) in an Account controller's VerifyEmail instead of implementing a repository with this code:

var user = context.Users.FirstOrDefault(u => u.Email == email);
return user ? true : false;  

Upvotes: 3

Views: 3654

Answers (2)

gemon01
gemon01

Reputation: 341

you must inject usermanager service from constructor

public class AJAXController : Controller
        {

            private readonly UserManager<ApplicationUser> _userManager;
            public AJAXController(UserManager<ApplicationUser> userManager)
            {
                _context = context;
                _userManager = userManager;
            }


    [AcceptVerbs("GET", "POST")]
            public async Task<IActionResult> VerifyEmail([FromQuery(Name = "Input.Email")]string email)
            {

                var resultuser =  await _userManager.FindByEmailAsync(email);
                if (resultuser.UserName != null)
                {
                    return Json($"l'Email {email} è già in uso.");
                }

                return Json(true);
            }

Upvotes: 2

Darxtar
Darxtar

Reputation: 2112

Yes you can wrap the UserManager in a repository.

I use it to verify user credentials like so:

    /// <summary>
    /// Verifies the user password
    /// </summary>
    /// <param name="user"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public async Task<Result<bool>> CheckUserPasswordAsync(User user, string password)
    {
        var result = new Result<bool>();
        try
        {
            result.Data = await _userManager.CheckPasswordAsync(user, password);
        }
        catch (Exception ex)
        {
            result.HandleException(ex, _logger);
        }
        return result;
    }

I have a UserService with the following constructor which allows me to perform actions on users:

    public UserService(
        RoleManager<ApplicationRole> roleManager,
        UserManager<User> userManager,
        SignInManager<User> signInManager,
        ILoggerFactory loggerFactory,
        IRepository repository)
    {
        _roleManager = roleManager;
        _userManager = userManager;
        _signInManager = signInManager;
        _logger = loggerFactory.CreateLogger<IUserService>();
        _repository = repository;
    }

And in Startup.cs you must add entity in your ConfigureServices Method:

                // add identity
                services.AddIdentity<User, ApplicationRole>()
                        .AddEntityFrameworkStores<BlogCoreContext>();

You can follow the same logic for your FindByEmailasync method ;)

Hope this helps and happy coding!

Upvotes: 1

Related Questions