简体   繁体   中英

UserManager.CreateAsync .Success always returns false

I'm trying to add users programmatically to the AspNetUsers table in my ASP.Net MVC 5.0 app using the following function:

private async Task AddUser(DataImportMember member)
{
    var user = new ApplicationUser
    {
        UserName = member.Email,
        Email = member.Email,
        UserType = UserType.IsMember
    };

    var password = RandomPassword.Generate();
    var result = await this.UserManager.CreateAsync(user, password);
    if (result.Succeeded)
    {
        await this.UserManager.AddToRoleAsync(user.Id, MyApp.IsMember);
    }
}

But whenever I call this.UserManager.CreateAsync , result.Succeed is always false. I've checked the AspNetUsers table and as expected, the user is not added.

Any ideas how I can figure out what's wrong and how to resolve it?

Thanks.

UserManager.CreateAsync returns an IdentityResult that would also contain any errors why the action was not successful. You should check the result error messages to find out why the action failed.

var result = await this.UserManager.CreateAsync(user, password);
if (result.Succeeded) {
    await this.UserManager.AddToRoleAsync(user.Id, MyApp.IsMember);
} else {
    var errors = result.Errors;
    var message = string.Join(", ", errors);
    ModelState.AddModelError("", message);
}

You can put try catch for checking the actual error.

   try{
        var result = await this.UserManager.CreateAsync(user, password);
    }
    catch(exception ex)
    {
     through ex;
    }

After getting the exact error it will be better to remove the try catch block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM