我正在尝试在Angular project template with ASP.NET Core中实现SendGrid。
我正在使用此示例:Account confirmation and password recovery in ASP.NET Core
不幸的是我总是收到此错误(状态:500):
System.InvalidOperationException:尝试激活“MyWebApp.Controllers.AuthenticationController”时无法解析类型“MyWebApp.Extensions.EmailSender”的服务
这是控制器:
[HttpPost]
public async Task<IActionResult> Register([FromBody]RegistrationViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var userIdentity = _mapper.Map<AppUser>(model);
var result = await _userManager.CreateAsync(userIdentity, model.Password);
if (!result.Succeeded)
return new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState));
//Enable account confirmation
var code = await _userManager.GenerateEmailConfirmationTokenAsync(userIdentity);
var callbackUrl = Url.EmailConfirmationLink(userIdentity.Id, code, Request.Scheme);
await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);
//await _appDbContext.SaveChangesAsync();
return new OkObjectResult("Account created");
}
还有EmailSender:
public class EmailSender : IEmailSender
{
public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)
{
Options = optionsAccessor.Value;
}
public AuthMessageSenderOptions Options { get; } //set only via Secret Manager
public Task SendEmailAsync(string email, string subject, string message)
{
return Execute(Options.SendGridKey, subject, message, email);
}
public Task Execute(string apiKey, string subject, string message, string email)
{
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress(<email-address>, <name>),
Subject = subject,
PlainTextContent = message,
HtmlContent = message
};
msg.AddTo(new EmailAddress(email));
return client.SendEmailAsync(msg);
}
}
我尝试直接在代码中编写apiKey
,但结果相同。
我已经在数据库中成功添加了一个用户,但是没有SendGrid。
答案 0 :(得分:2)
确保服务及其抽象已在服务集合中注册,以便服务提供商了解如何解决这些问题
Startup.ConfigureServices
services.AddSingleton<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);