Generate link to confirm email is returning null in ASP.NET Core API

642 Views Asked by At

I'm trying to generate an email confirmation link on an Identity Core user record. For that, I'm trying to generate a link with data from the controller and action of the MVC application in addition to the email and token information, however, the Url.Link method has always returned null as a response.

[HttpPost("reenviaemail")]
[AllowAnonymous]
public async Task<Boolean> ReenviaEmail(string Email)
{
  try
  {
    var user = await _userManager.FindByEmailAsync(Email);

    if(user != null)
    {
      var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
      var confirmationEmail = Url.Link("recuperar", new { Controller = "User", Action = "ConfirmEmailAddress", token = token, email = user.Email });
      EnviarEmail.SendMail(Email, user.NomeCompleto, confirmationEmail);
      return true;
    }
    else
    {
      return false;
    }
  }
  catch (Exception ex)
  {
    return false;
  }
}

I tried other methods like ActionLink and Action, but none of them worked.

1

There are 1 best solutions below

0
ChizT On

this is the code documentation of Url.Link

// Parameters:
//   routeName:
//     The name of the route that is used to generate URL.
//
//   values:
//     An object that contains route values.

as per your code above

Url.Link("recuperar", new { Controller = "User", Action = "ConfirmEmailAddress", token = token, email = user.Email });

you are passing Controller and Action properties that are not part of your route values(the parameters of your action method). Url.Link() returns null if it did not find the route that you have specified, in this case RouteName + Route values.

You might want to change your code to:

Url.Link("recuperar", new { token = token, email = email });

then your action method should look something link this

[Route("validateemail", Name = "recuperar")]
public IActionResult ValidateEmail(string token, string email)
{
     //more code
}