ASP.Net MVC使用事件处理程序发送电子邮件

时间:2019-02-11 19:49:38

标签: asp.net-mvc asynchronous events

我在YT上观看了一些视频,这些视频描述了SMS Manager的Event Hanlders。我想用Email Manager建立类似的东西:

public class OfferEmailManager
{
        public async void OnSecurityDepositAdded(object source, SecurityDepositEventArgs eventArgs)
        {
            EmailObject email = new EmailObject();
            //preparing email object (subject, body, from, to)
            var result = await EmailAPI.Instance.SendEmail(email);
        }

        private string PrepareSecurityDepositAddMail(SecurityDepositEventArgs eventArgs)
        {
            //preparing mail body
        }
}

似乎一切正常,但是发送电子邮件是异步的,我不得不使OnSecurityDepositAdded异步。当SecurityDeposit添加到控制器中的数据库时,我想发送电子邮件:

public EventHandler<SecurityDepositEventArgs> SecurityDepostAdded;
    protected virtual void OnSecurityDepositAdded(SecurityDeposit securityDeposit, Offer offer)
    {
       SecurityDepositAdded?.Invoke(this, new SecurityDepositEventArgs()
       {
           //values
       });
    }

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> AddSecurityDeposit(SecurityDepositCreateViewModel model)
        {
            Offer offer = db.Offers.Find(model.ID);
            OfferEmailManager manager = new OfferEmailManager();
            SecurityDepositAdded += manager.OnSecurityDepositAdded;
            SecurityDeposit securityDeposit = new SecurityDeposit()
            {
                // values
            };
            db.SecurityDeposits.Add(securityDeposit);
            try
            {
                db.SaveChanges();
                OnSecurityDepositAdded(securityDeposit, offer);
                return RedirectToAction("Details", new { id = model.ID });
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = ex.Message;
                return View(model);
            }
        }

最后,它非常适合return RedirectToAction,我收到了电子邮件,但也有例外情况

  

异步完成的异步模块或处理程序   操作仍在等待中

如何处理此异常?

0 个答案:

没有答案