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
CodePudding user response:
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.