如何在asp.net MVC视图中显示SmtpClient.SendAsync()的实际结果?

时间:2013-01-19 21:50:03

标签: asp.net-mvc razor callback smtpclient sendasync

SmtpClient.SendAsync()调用不会像SmtpClient.Send()那样返回结果,但会继续并且无法在视图中显示结果。那么如何在此处挂钩回调函数,获取发送电子邮件结果/错误并在视图中显示?

感谢。

1 个答案:

答案 0 :(得分:0)

您有两种选择:

a)改为呼叫SmtpClient.Send()

b)从异步控制器调用SmtpClient.SendAsync()

public class HomeController : AsynController
{
    [HttpPost]
    public void IndexAsync()
    {
        SmtpClient client = new SmtpClient();

        client.SendCompleted += (s,e) =>
        {
            AsyncManager.Parameters["exception"] = e.Error;
            AsyncManager.OutstandingOperations.Decrement();
        };

        AsyncManager.OutstandingOperations.Increment();

        client.Send(GetMessage());
    }

    public void IndexCompleted(Exception exception)
    {
        if (exception != null)
        {
            ModelState.AddError("", "Email send failed");
            return View();
        }
        else
        {
            return Redirect("Complete");
        }
    }
}