即使try块没有异常,Catch块也会执行?

时间:2014-12-24 12:30:31

标签: c# try-catch

我正在尝试通过goDaddy邮件服务器发送邮件。邮件正在发送(我在我的邮箱中收到它)但是catch块正在执行并将我带到查询字符串msg的联系页面,因为"失败"

    protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["username"] != null && Request.QueryString["email"] != null && Request.QueryString["msg"] != null)
    {
        try
        {
            string name = Request.QueryString[0];
            string email = Request.QueryString[1];
            string msg = Request.QueryString[2];
            SmtpClient smtp = new SmtpClient("relay-hosting.secureserver.net", 25);
            //smtp.EnableSsl = false;
            smtp.Send("feedback@solutionpoint98.com", "b.soham1991@gmail.com", "feedback", "Name:" + name + "\n e-mail:" + email + "\n Subject:" + msg);
            Response.Redirect("contact.html?msg=success");
        }
        catch(Exception ex)
        {
            Response.Redirect("contact.html?msg=fail");
        }
    }
    else
    {
        Response.Redirect("contact.html");
    }
}

如果邮件正在发送,则不应该重定向到" contact.html?msg = success"?

1 个答案:

答案 0 :(得分:2)

问题是你的第一个Response.Redirect()实际上是在抛出一个ThreadAbortException。这是因为.Redirect内部调用了Response.End方法,在这种情况下提前结束了响应。

执行此操作的正确方法是使用重载的Response.Redirect(string url,bool endResponse),它允许您通过将endResponse设置为false来禁止对Response.End的内部调用...这将防止此错误被抛出。

本MS支持文章中涵盖了这一点:http://support.microsoft.com/kb/312629/EN-US/

只需修改您的代码,如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["username"] != null && Request.QueryString["email"] != null && Request.QueryString["msg"] != null)
    {
        try
        {
            string name = Request.QueryString[0];
            string email = Request.QueryString[1];
            string msg = Request.QueryString[2];
            SmtpClient smtp = new SmtpClient("relay-hosting.secureserver.net", 25);
            //smtp.EnableSsl = false;
            smtp.Send("feedback@solutionpoint98.com", "b.soham1991@gmail.com", "feedback", "Name:" + name + "\n e-mail:" + email + "\n Subject:" + msg);
            Response.Redirect("contact.html?msg=success", false);
        }
        catch(Exception ex)
        {
            Response.Redirect("contact.html?msg=fail", false);
        }
    }
    else
    {
        Response.Redirect("contact.html", false);
    }
}