MVCMailer SendAsync() fails with Amazon SES

前端 未结 1 944
清歌不尽
清歌不尽 2021-01-21 07:56

If I use Send() with MVCMailer, my SES works fine, but SendAsync() shows the error message below, does anyone know of a work around for this? THanks!

System.Net.         


        
相关标签:
1条回答
  • 2021-01-21 08:25

    This error is by design. You can turn this off globally:

    <appSettings>
      <add key="aspnet:AllowAsyncDuringSyncStages" value="false" />
    </appSettings>
    

    reference http://msdn.microsoft.com/en-us/library/hh975440.aspx

    Something else to consider is using a Task to do the async in the background, decoupling it from the scheduler that ASP.Net uses. Using this method, you wouldn't need to change the appSetting.

    using Mvc.Mailer;
    ...
    public ActionResult SendWelcomeMessage()
    {
        Task.Factory.StartNew(() => UserMailer.Welcome().SendAsync());
        return RedirectToAction("Index");
    }
    

    Edit

    Enabling AllowAsyncDuringSyncStages or using the Task Parallel Library both have potential drawbacks. Using AsyncController does not have either drawback. Thanks @StephenCleary for challenging my answer.

    public class HomeController : AsyncController
    {
      public void SendMessageAsync()
      {
        var client = new SmtpClientWrapper();
        client.SendCompleted += (sender, args) => 
          AsyncManager.OutstandingOperations.Decrement();
        AsyncManager.OutstandingOperations.Increment();
        new UserMailer().Welcome().SendAsync("", client);
      }
    
      public ActionResult SendMessageCompleted()
      {
        return View();
      }
    }
    
    0 讨论(0)
提交回复
热议问题