Matthew Warr
Matthew Warr

Reputation: 168

.NET Core 2 Identity CreateAsync Error Catching

I am getting an error when trying to CreateAsync a user.

var create = await _userManager.CreateAsync(user, model.Password);

There is a property I can access on the IdentityResult called errors. However I can't work out how to access it. Any idea how I can catch it so I can see what it is erroring on?

I've posted the full controller code below. For some reason whenever I try and do anything with my var create it just ignores it. I can't even step into it.

namespace TechsportiseOnline.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]/[action]")]
    public class RegistrationController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly IConfiguration _configuration;
        private readonly IOptions<JWTSettings> _jwtConfig;
        private readonly IEmailSender _emailSender;

        public RegistrationController(
              UserManager<ApplicationUser> userManager,
              SignInManager<ApplicationUser> signInManager,
              IConfiguration configuration,
              IOptions<JWTSettings> jwtConfig,
              IEmailSender emailSender)
                    {
                        _userManager = userManager;
                        _signInManager = signInManager;
                        _configuration = configuration;
                        _jwtConfig = jwtConfig;
                        _emailSender = emailSender;

        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Register([FromBody] RegisterModel model)
        {
            if (ModelState.IsValid)
            {

                var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email = model.Email,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    MobileNumber = model.MobileNumber,
                    Marketing = model.Marketing,
                    Newsletter = model.Newsletter
                };

                var result = new CreateUserResult();

                var    create = await _userManager.CreateAsync(user, model.Password);




                if (create.Succeeded == true)
                {

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code.ToString(), Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);


                    //await _createContact.CreateContactAsync(model.Email, model.FirstName, model.LastName, model.Marketing, model.Newsletter);
                    var fields = new Dictionary<string, string>();
                    fields.Add("firstname", model.FirstName);
                    fields.Add("lastname", model.LastName);
                    fields.Add("newsletter", model.Newsletter.ToString());
                    fields.Add("marketing", model.Marketing.ToString());
                    string publicaccountid = "55ebcc8b-b23f-4843-9dcb-1df08811de65";
                    var createcontact = ElasticEmailClient.Api.Contact.AddAsync(publicAccountID: publicaccountid, email: model.Email, field: fields);



                    //await _signInManager.SignInAsync(user, isPersistent: false);
                    return CreatedAtRoute("CreateAccount", model);
                }
                else
                {
                    return BadRequest("Could not register account");
                }
            }
            else
            {
                return BadRequest("The model is invalid");
            }
        }       
    }


}

Upvotes: 1

Views: 2339

Answers (2)

Bridget Arrington
Bridget Arrington

Reputation: 444

Set your breakpoint on if (create.Succeeded == true) and inspect the create object or add an else statement to read the errors. Here is the code I use to log my errors.

var result = await _userManager.CreateAsync(newUser, "Password123!");

if (result.Succeeded)
{
   //do stuff
}
                
foreach (var error in result.Errors)
{
   _logger.LogWarning("Code: " + error.Code + " " + error.Description);
}

Upvotes: 0

David Liang
David Liang

Reputation: 21536

This is my sample code: I am using MediatR to (try to) separate queries and commands.

CreateUserByAdminHandler

public class CreateUserByAdminHandler : IAsyncRequestHandler<CreateUserByAdmin, CreateUserResult>
{
    private readonly UserManager<AppUser> _userManager;

    public CreateUserByAdminHandler(UserManager<AppUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<CreateUserResult> Handle(CreateUserByAdmin command)
    {
        var result = new CreateUserResult();

        try
        {
            var appUser = new AppUser
            {
                UserName = command.Username.Trim(),
                FirstName = command.FirstName.Trim(),
                LastName = command.LastName.Trim(),
                Email = command.Email,
                PhoneNumber = command.PhoneNumber,
                Status = UserStatus.Active
            };

            var createResult = await _userManager.CreateAsync(appUser, command.Password);
            if (!createResult.Succeeded)
            {
                // IdentityResult has Errors property, which is a list of 
                // IdentityError. IdentityError has Code and Description
                // property. It's up to you to select whichever property 
                // for the error message.

                result.AddErrors(createResult.Errors.Select(ier => ier.Description));
                return result;
            }

            result.NewUser = appUser;
        }
        catch (Exception ex)
        {
            result.SetException(ex);
        }

        return result;
    }
}

Upvotes: 1

Related Questions