【发布时间】:2016-04-22 19:14:33
【问题描述】:
我一直在努力想弄清楚这里出了什么问题。我是 C# 的新手,对 MVC 来说也很新。我的网站需要一个小而简单的电子邮件联系表。我不完全确定押韵或原因是什么,但控制器将注册表单的所有字段,但会跳过 smtp.Send(msg); 并直接跳转到 catch 方法。我尝试在我读过的[POST] 之后添加[GET] 方法有帮助,但仍然没有运气。我感觉这是 smtp 端口或主机的问题,但我找不到任何文档。
另外,我也尝试为按钮功能添加一些 sn-ps,但也没有运气。任何帮助都会很棒。
型号
public class ContactModels
{
[Required(ErrorMessage ="Your name is required")]
public string FullName { get; set; }
[Required(ErrorMessage = "Your email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "Your phone number is required")]
public string Phone { get; set; }
[Required(ErrorMessage = "You must type a message")]
public string Comment { get; set; }
}
查看
<div class="col-md-4">
<p><strong>Phone: </strong>586.xxx.xxxx</p>
<p><strong>Email: </strong><a href="mailto:Tom@blank.com">example@example.com</a></p>
<p><strong>Address: </strong>Address Here</p>
<h3>Connect with us through Email </h3>
@using (Html.BeginForm(FormMethod.Post))
{
@Html.ValidationSummary(true)
<div class="row">
@Html.LabelFor(model=>model.FullName, "Name: ")
@Html.EditorFor(model=>model.FullName)
@Html.ValidationMessageFor(model=>model.FullName)
</div>
<div class="row">
@Html.LabelFor(model=>model.Email, "Email: ")
@Html.EditorFor(model=>model.Email)
@Html.ValidationMessageFor(model=>model.Email)
</div>
<div class="row">
@Html.LabelFor(model=>model.Phone, "Phone: ")
@Html.EditorFor(model=>model.Phone)
@Html.ValidationMessageFor(model=>model.Phone)
</div>
<div class="row">
@Html.LabelFor(model=>model.Comment, "Message: ")
@Html.TextAreaFor(model=>model.Comment)
@Html.ValidationMessageFor(model=>model.Comment)
</div>
<div class="row">
<input type="submit" value="Send"/>
<input type="reset" value="Reset"/>
</div>
}
</div>
控制器
public ActionResult Contact()
{
return View();
}
[HttpPost]
public ActionResult Contact(Models.ContactModels c)
{
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress(c.Email.ToString());
StringBuilder sb = new StringBuilder();
msg.To.Add("myEmailHere@gmail.com");
msg.Subject = "Contact Us";
msg.IsBodyHtml = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 993;
sb.Append("Name: " + c.FullName);
sb.Append(Environment.NewLine);
sb.Append("Email: " + c.Email);
sb.Append(Environment.NewLine);
sb.Append("Phone: " + c.Phone);
sb.Append(Environment.NewLine);
sb.Append("Comment: " + c.Comment);
sb.Append(Environment.NewLine);
msg.Body = sb.ToString();
smtp.Send(msg);
msg.Dispose();
return View("Success");
}
catch(Exception)
{
return View("Error");
}
}
return View();
}
【问题讨论】:
-
将
catch(Exception)更改为catch(Exception ex)并在此处设置断点并检查 ex 变量以获取有关错误的更多信息。 -
@Shyju ex 变量读取一个空值
-
catch(Exception ex)中的ex变量应该显示异常类型、消息,最重要的是堆栈跟踪,它应该准确地告诉你哪个方法失败了。很可能您正在使用具有null值的这些属性之一进行上述字符串连接。此外,您应该使用 using 块或 finally 块(如SmtpClient)处理所有一次性用品。 -
'A from address must be specified' 当我将鼠标悬停在 ex 遇到断点时。
-
你去。我希望错误信息很明显。
标签: c# asp.net-mvc