I am getting an exception although everything seems to be fine.
Exception: NullReferenceException: Object reference not set to an instance of an object.
Code breaks at:
await _userManager.AddToRoleAsync(user, Input.Role);
Code:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = CreateUser();
await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
if (Input.Role != null)
{
await _userManager.AddToRoleAsync(user, Input.Role);
}
else
{
await _userManager.AddToRoleAsync(user, Roles.Role_User_Cust);
}
var userId = await _userManager.GetUserIdAsync(user);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page("/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
}
}
}
I didn't see how the
CreateUser()
works but there's a problem. Asuser
is a newly created instance. You should get "user_created" the from database again to get a full user object.And if Role hasn't been created yet. you need to inject the rolemanager to create a new role.