我有一种发送电子邮件的方法,该方法利用了SmtpClient
。在此方法的某一时刻,我有以下await smtpClient.SendMailAsync (mail);
。根据情况,可以通过我的控制器进行以下调用:
[HttpPost]
[AllowAnonymous]
[ValidateJsonAntiForgeryToken]
public async Task<ActionResult> RegisterParticipant(RegisterIndexBaseVm attendee)
{
if (attendee == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
if (ModelState.IsValid)
{
attendee.EventId = Int32.Parse(Session["id"].ToString());
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client.PostAsync("Register/RegisterAttendee", new StringContent(JsonConvert.SerializeObject(Mapper.ToParticipant(attendee)), Encoding.UTF8, "application/json"));
if (Res.IsSuccessStatusCode)
{
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<EmailTemplateDTO>(EmpResponse);
if (result.NotError == false)return Json(new { success = false, message = Constants.CulqiResponses[result.Response] }, JsonRequestBehavior.AllowGet);
if (string.IsNullOrEmpty(result.InvoiceInstitution))
{
if (result.SendEmail == true) MailHelper.SendMail(Enumerables.MailAction.EventRegisterSuccess, result);
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
else
{
if (result.SendEmail == true) MailHelper.SendMail(Enumerables.MailAction.EventRegisterSuccessWithInvoice, result);
return Json(new { success = true, message = "Registro Exitoso" }, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
}
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
在Web应用程序中,我具有一个AJAX,该AJAX执行对使用参数async: true
的控制器的调用,但始终会出现500错误。我不太清楚原因,也不知道如何正确调用每个方法和类以获得正确的结果。
$.ajax({
type: 'POST',
url: url,
headers: headers,
dataType: 'json',
async: true,
data: { attendee: enviar },
success: function (response) {
$('#payment').modal('hide');
if (payType === 'Culqui') {
resultdiv("", 'success');
}
else {
resultdiv("", 'warning');
}
},
error: function (result) {
$('#payment').modal('hide')
resultdiv("", 'error');
}
});
答案如下:
An asynchronous module or handler completed while an asynchronous operation was still pending.
但是,电子邮件的发送不会带来任何不便。发送电子邮件的方法必须具有以下public static async void SendMail
,我希望控制器不会对此发送任何真实的响应。
感谢您的提前支持。
答案 0 :(得分:1)
如@binki在此post中所建议:
var originalSynchronizationContext = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
//... call your method here!
}
finally
{
SynchronizationContext.SetSynchronizationContext(originalSynchronizationContext);
}
这是因为异步方法跟踪它们的完成,甚至异步无效。他们通过在启动时向SynchronizationContext注册并在返回时将操作标记为完成来完成此操作。 ASP.NET会跟踪所有已创建的操作,并要求它们在操作返回之前完成所有操作,否则它将向HTTP客户端返回错误。