2

I try to use Identity in asp.net core API, everything works fine except I couldn't find a way to create call back url for email confirmation. I searched a lot, but no one implemented Identity with email confirmation in ASP.NET core API.

Here's my RegisterUser code:

var user = new ApplicationUser
        {
            Name = model.Name,
            Email = model.Email,
            UserName = model.Email
        };

var result = await _userManager.CreateAsync(user, model.Password);

if (result.Succeeded)
{
    await _userManager.AddToRoleAsync(user, "User");

    var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
    var callbackurl = Url.RouteUrl("ConfirmEmail", new { userId = user.Id, token = token }, protocol: Request.Scheme);
    var message = new Message(
              new string[] { model.Email },
              Messages.Email_Confirmation,
               Messages.Email_CreateUser_Body + "<a href=\"" + callbackurl + "\">link</a>"
            );

    _emailSender.SendEmail(message);

    return Ok();
}

The above code 'callbackurl' return null. I tried other methods for creating url but it won't work.

Thanks in advance for your help

3
  • Have you try to use Url.Page ? Commented May 27, 2022 at 8:30
  • thanks for your reply.I used Url.page and I got this error.The relative page path 'ConfirmEmail' can only be used while executing a Razor Page. I want to use in API controller Commented May 27, 2022 at 8:47
  • The effect of Url.page and Url.RouteUrl should be similar, this should not be the key to this problem, please use the previous Url.RouteUrl, thank you~ Commented May 27, 2022 at 8:53

1 Answer 1

1

I found the root cause, it is because you are missing routing configuration.

In .net6, program.cs

...
app.MapControllers();

// add this code
app.MapControllerRoute(
    name: "ConfirmEmail",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

This is just my test code, I reproduce the issue in my local, and I faced the issue, and after add app.MapControllerRoute, it works.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm extremely grateful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.