Why I am getting NullReferenceException

107 Views Asked by At

I am getting an exception although everything seems to be fine.

Exception: NullReferenceException: Object reference not set to an instance of an object.

error image

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);
            }
        }
    }
2

There are 2 best solutions below

0
On

I didn't see how the CreateUser() works but there's a problem. As user is a newly created instance. You should get "user_created" the from database again to get a full user object.

            IdentityUser user_created = _userManager.FindByEmailAsync(Input.Email).Result;                   
            _userManager.AddToRoleAsync(user_created, Input.Role);

And if Role hasn't been created yet. you need to inject the rolemanager to create a new role.

_roleManager.CreateAsync(Input.Role);
1
On

If the exception is thrown at

await _userManager.AddToRoleAsync(user, Input.Role);

there are only two objects that can throw a NullReferenceException:

  • _userManager, because the AddToRoleAsync method call isn't possible if _userManager is null.
  • Input, because the Role property access isn't possible if Input is null.

The stack trace indicates that the exception is thrown deep within AddToRoleAsync, so this means that _userManager is not null. Therefore, Input must be null.

In order to address that problem, you'll need to either prevent Input from being null, or take an alternative course of action if you detect that Input is null.