在我的MVC应用程序中,我有一个功能是让客户向各自的所有者/经销商发送消息。消息模型如下:
以下是我的
public class Messages
{
public string MessageFrom { get; set; }
public string MessageUserEmailID { get; set; }
public string MessageUserContactNum { get; set; }
public string Message { get; set; }
public int UserID { get; set; }//Admin user id
public string propertyName { get; set; }
}
以下是我的
Controller
方法,将通过AJAX
调用:
- 我会将消息存储在数据库中
- 发送电子邮件通知管理员
- 向用户返回一个
Json
响应。
HomeController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SendMessage([Bind(Prefix = "messageModel")]Messages model)
{
private SendNotification notify = new SendNotification();
if (ModelState.IsValid)
{
using (db)
{
tblMessage messageModel = new tblMessage();
//....
//....
//....
//fill the messageModel with the model values
db.tblMessages.Add(messageModel);
db.SaveChanges();
string toAddress = db.tblUsers.Where(u => u.UserId == model.UserID).Select(x => x.UserEmailID).FirstOrDefault();
if (!string.IsNullOrEmpty(toAddress))
{
notify.NotifyUser(toAddress, model.MessageUserContactNum, model.propertyName, model.Message, model.MessageFrom, model.MessageUserEmailID, "Kemmale Engineers' Notification - You have a message");
}
return Json(new { result = true, message = "Message sent! Thank you! We will get back to you soon!" }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { result = false, message = "Server issue! Please try again later" }, JsonRequestBehavior.AllowGet);
}
SendNotification
类包含以下 NotifyUser
方法:
public void NotifyUser(string toAddress, string userPhoneNum, string propertyName, string userMessage, string userName, string userContactEmail, string subject)
{
using (MailMessage mail = new MailMessage())
{
string Password = WebConfigurationManager.AppSettings["ApplicationEmailPassword"];
var securePassword = new SecureString();
Array.ForEach(Password.ToArray(), securePassword.AppendChar);
securePassword.MakeReadOnly();
mail.To.Add(toAddress);
mail.From = new MailAddress(WebConfigurationManager.AppSettings["ApplicationEmailID"]);
mail.Subject = subject;
mail.Body = Convert.ToString(ConstructBody(userMessage, propertyName, userPhoneNum, userContactEmail, userName));
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential(Convert.ToString(mail.From), securePassword);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
}
}
您可以看到,Notify
的返回类型是void
。现在我该如何在不等待Notify
方法执行的情况下向用户返回Json
消息呢?因为让用户等待与他无关的内部过程完成非常过时。我正在考虑使用异步任务
,但不确定如何在这里实现。
.net framework 4
,所以我不得不使用Task.Factory.StartNew(() => {NotifyUser();});
。您可以将其添加为答案,这样我就可以接受它了。 - Guruprasad J Rao