0

I'm trying to add a user in my database but when I create it it is not added and it doesn't give me an error message. When I add a breakpoint to the CeateUser method the code is running but when I add a breakpoint on the result condition, the code is never reached.
Here's my PageModel
 public class AddUserModel : PageModel
{
    [BindProperty]
    public NewAccountInput AccountInput { get; set; }

    private UserManager<AdminUser> UserManager { get; set; }

    public AddUserModel(UserManager<AdminUser> userManager)
    {
        UserManager = userManager;


    }

    public void OnPost()
    {

        if(AccountInput.ComfirmationPassword != AccountInput.Password)
        {
            return;
        }
        _ = CreateUser();



    }

    public async Task<bool> CreateUser()
    {
       var result = await UserManager.CreateAsync(new AdminUser()
        {
            Email = AccountInput.Email,
            FirstName = AccountInput.UserName,
            LastName = AccountInput.UserName,
            UserName = AccountInput.Email
        }, AccountInput.Password);


        if (result.Succeeded)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
  • 1
    Try to make method `OnPost` asynchronous and call method CreateUser using `await` – Boris Makhlin Apr 02 '21 at 11:58
  • Thank you, now I have an error: "Cannot access a disposed object.\nObject name: 'MySqlConnection'." – DimitriTimoz Apr 02 '21 at 12:07
  • The problem is pretty simple. Method CreateUser throws an exception. You didn't see this exception because you didn't call method CreateUser with `await`. See this question to understand why it works so: https://stackoverflow.com/questions/60560761/c-calling-async-method-without-await-will-not-catch-its-thrown-exception – Boris Makhlin Apr 02 '21 at 12:15
  • Since I added an await I had this error, so the problem is maybe not the await. – DimitriTimoz Apr 02 '21 at 12:33
  • The problem is inside of your method `CreateAsync` – Boris Makhlin Apr 02 '21 at 16:09

1 Answers1

0

The solution is because the method OnPost must be of type Task.

public async Task OnPost()
{

      if(AccountInput.ComfirmationPassword != AccountInput.Password)
      {
           return;
      }
      await CreateUser();
 }