Using Postal and Hangfire in Subsite

扶醉桌前 提交于 2019-12-06 10:49:57

I followed the directions here http://docs.hangfire.io/en/latest/tutorials/send-email.html to send my email. The method in the tutorial is below

    public static void NotifyNewComment(int commentId)
{
// Prepare Postal classes to work outside of ASP.NET request
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));

var emailService = new EmailService(engines);

// Get comment and send a notification.
using (var db = new MailerDbContext())
{
    var comment = db.Comments.Find(commentId);

    var email = new NewCommentEmail
    {
        To = "yourmail@example.com",
        UserName = comment.UserName,
        Comment = comment.Text
    };

    emailService.Send(email);
}
}

I found the issue was that the FileSystemRazorViewEngine was not being used bty postal. To get the this to work I had to make sure that the FileSystemRazorViewEngine was the first engine in the available. I then removed it because I did not want it to be the default engine. Below is my updated method.

    public static void NotifyNewComment(int commentId)
{
// Prepare Postal classes to work outside of ASP.NET request
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var eng = new FileSystemRazorViewEngine(viewsPath));
ViewEngines.Engines.Insert(0, eng);

var emailService = new EmailService(engines);

// Get comment and send a notification.
using (var db = new MailerDbContext())
{
    var comment = db.Comments.Find(commentId);

    var email = new NewCommentEmail
    {
        To = "yourmail@example.com",
        UserName = comment.UserName,
        Comment = comment.Text
    };

    emailService.Send(email);
    ViewEngines.Engines.RemoveAt(0)
}
}
Jeff

Below is another possible solution that I think is more elegant than above. It also resolves an issue that appears when accessing the MVC application while the background process is being executed.

public static void SendTypedEmailBackground()
{
    try
    {
        var engines = new ViewEngineCollection();
        var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));

        var eng = new FileSystemRazorViewEngine(viewsPath);
        engines.Add(eng);

        var email = new WebApplication1.Controllers.EmailController.TypedEmail();
        email.Date = DateTime.UtcNow.ToString();
        IEmailService service = new Postal.EmailService(engines);
        service.Send(email);

    }
    catch(Exception ex)
    {
        throw ex;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!