Cic*_*cio 3 c# postal asp.net-mvc-5 hangfire
我有一个MVC应用程序,正在尝试使用Hangfire和邮政发送电子邮件。该电子邮件必须在注册后发送。注册工作正常,但是我运行的作业仍然排队,并且我没有收到任何电子邮件。所以在我的MVC控制器中,我有以下代码:
public async Task<ActionResult> Register(RegisterViewModel model)
{
//register correctly the user
//I send the email
BackgroundJob.Enqueue(() =>
NotifyRegistration(user.Id, user.UserName, user.Email)
);
...
}
[AutomaticRetry(Attempts = 5)]
public async Task NotifyRegistration(string userId, string username, string email)
{
//I calculate callbackUrl
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
var emailService = new EmailService(engines);
var emailToSend = new NewRegisteredUserEmail
{
To = email, UserName = username, CallbackUrl = callbackUrl
};
emailService.Send(emailToSend);
}
Run Code Online (Sandbox Code Playgroud)
我无法调试NotifyRegistration方法。我不知道为什么 我正在使用邮政,所以EmailService不是我的实现。这里是我如何配置smtp服务:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="smtp.live.com" port="25" enableSsl="true" userName="***" password="***"></network>
</smtp>
</mailSettings>
</system.net>
Run Code Online (Sandbox Code Playgroud)
如果我运行hangfire仪表板,我看到工作已入队
但是没有其他事情发生。我错过了什么发送电子邮件?
谢谢
更新 在startup.cs中,我这样写:
var options = new SqlServerStorageOptions
{
QueuePollInterval = TimeSpan.FromSeconds(1)
};
GlobalConfiguration.Configuration
.UseSqlServerStorage("DbConnectionString", options)
.UseFilter(new LogEmailFailureAttribute());
app.UseHangfireDashboard();
app.UseHangfireServer();
Run Code Online (Sandbox Code Playgroud)
更新2 我以这种方式转换了NotifyRegistration:
[AutomaticRetry(Attempts = 5)]
public async Task NotifyRegistration(string userId, string username, string email, EmailService emailService)
{
//I calculate callbackUrl
var emailToSend = new NewRegisteredUserEmail
{
To = email, UserName = username, CallbackUrl = callbackUrl
};
emailService.Send(emailToSend);
}
Run Code Online (Sandbox Code Playgroud)
我发现了问题:
不支持sql server版本。我使用的是2005。支持的数据库是2008R2及更高版本:http : //docs.hangfire.io/zh-CN/latest/configuration/using-sql-server.html
方法NotifyRegistration必须是静态的:https ://discuss.hangfire.io/t/jobs-in-enqueue-state-most-never-run/2367/4
。
[AutomaticRetry(Attempts = 5)]
public static void NotifyRegistration(string userId, string username, string email, EmailService emailService)
{
//I calculate callbackUrl
var emailToSend = new NewRegisteredUserEmail
{
To = email, UserName = username, CallbackUrl = callbackUrl
};
emailService.Send(emailToSend);
}
Run Code Online (Sandbox Code Playgroud)