hello hello - 1 month ago 27
ASP.NET (C#) Question

Send email from async method

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

Answer

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!