1

If I'm trying to send an email immediately a new email has been confirmed, how to I go about it ? The piece of code below is what I have in ConfirmEmail method. When I run the code, I get Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. on await UserManager.SendEmailAsync(userId, "API", "API Code is: " + user.ApiCode);

I think UserManager.FindById is not returning anything, but not sure how to go about it.

Any pointers/ideas will help.

public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
    if (userId == null || code == null)
    {
        return View("Error");
    }
    var result = await UserManager.ConfirmEmailAsync(userId, code);

    var user = UserManager.FindById(User.Identity.GetUserId());
    await UserManager.SendEmailAsync(userId, "API", "API Code is: " + user.ApiCode);

    return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
hello
  • 1,168
  • 4
  • 24
  • 59
  • 1
    My guess is that the User is not authenticated yet so User.Identity is null and hence the NullReferenceException. Have you tried var user = UserManager.FindById(userId); instead? – Karel Tamayo Oct 27 '16 at 03:58
  • You haven't checked whether `user` is null before using it – Adrian Sanguineti Oct 27 '16 at 03:59
  • have you debugged?. How did you implement the user sign in process? are you using your own MembershipProvider implementation? – jmesolomon Oct 27 '16 at 03:59
  • Possible duplicate of [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) – Adrian Sanguineti Oct 27 '16 at 03:59
  • @KarelTamayo Can you create a proper answer? Your comment helped solved the problem. Thanks – hello Oct 27 '16 at 04:05

1 Answers1

2

With the info you provided I guess maybe the problem is that the user is not authenticated and therefore User.Identity will return null, hence the NullReferenceException.

You could try to fetch the user information with the id you're receiving in the action parameter userId instead.

public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
    if (userId == null || code == null)
    {
        return View("Error");
    }
    var result = await UserManager.ConfirmEmailAsync(userId, code);

    //var user = UserManager.FindById(User.Identity.GetUserId());
    var user = UserManager.FindById(userId); //use the received parameter to get the user
    await UserManager.SendEmailAsync(userId, "API", "API Code is: " + user.ApiCode);

    return View(result.Succeeded ? "ConfirmEmail" : "Error");
}

Hope this helps!

Karel Tamayo
  • 3,690
  • 2
  • 24
  • 30