"抛出异常:' System.Threading.ThreadAbortException'在mscorlib.dll"使用Response.Redirect()时

时间:2017-02-20 17:16:52

标签: c# asp.net exception mscorlib threadabortexception

在ASP.NET Web表单中按钮的OnClick方法中,我调用了Response.Redirect(),这会导致系统使用错误消息中止该线程:

Exception thrown: 'System.Threading.ThreadAbortException' in mscorlib.dll

在这里有一些与此类似的问题,使用我改变的解决方案:

Response.Redirect("~/UI/Home.aspx");

Response.Redirect("~/UI/Home.aspx", false);
Context.ApplicationInstance.CompleteRequest();

但是我仍然遇到同样的问题。使用调试器我运行了代码并且所有操作都成功执行,直到我调用Response.Redirect();.

点击功能

protected void btnLogin_Click(object sender, EventArgs e)
    {
        SiteUser s = null;
        try
        {
            string email = txtEmail.Text;
            string pwd = txtPwd.Text;
            s = DBConnection.login(email, pwd);                
        }
        catch (Exception ex)
        {
            Console.Write(ex);
            lblLoginError.Text = "Error logging in.";
        }
        if (s != null)
        {
            Session["UserSession"] = s;
            Response.Redirect("~/UI/Home.aspx", false);
            Context.ApplicationInstance.CompleteRequest();
        }
        else
        {
            lblLoginError.Text = "User not found. Please check your details and try again.";
        }
    }

有关为何会发生这种情况的任何想法?

2 个答案:

答案 0 :(得分:3)

我过去曾见过这个问题。理论上,如果您使用此代码,则不应该发生:

Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();

话虽这么说,我有时仍然会得到这些,这真的很令人惊讶。我猜测它有时会出现一个活动的finally块,以表示代码开始清理自己,尽管对你来说情况似乎并非如此。

我能想到的最好的解决方法是捕获错误并忽略它。

protected void btnLogin_Click(object sender, EventArgs e)
{
    try
    {
        SiteUser s = null;
        try
        {
            string email = txtEmail.Text;
            string pwd = txtPwd.Text;
            s = DBConnection.login(email, pwd);                
        }
        catch (Exception ex)
        {
            Console.Write(ex);
            lblLoginError.Text = "Error logging in.";
        }
        if (s != null)
        {
            Session["UserSession"] = s;
            Response.Redirect("~/UI/Home.aspx", false);
            Context.ApplicationInstance.CompleteRequest();
        }
        else
        {
            lblLoginError.Text = "User not found. Please check your details and try again.";
        }
    }
    catch(System.Threading.ThreadAbortException)
    {
        //Do nothing.  The exception will get rethrown by the framework when this block terminates.
    }
}

答案 1 :(得分:0)

如果会话在目标页面中没有包含特定元素,那么这就是我重定向引起的问题,在这种情况下它没有!仍然抛出异常,但不再导致明显的问题。

由于

相关问题