使用 Response.Redirect() 时“抛出异常:mscorlib.dll 中的‘System.Threading.ThreadAbortException’”

Joe*_*eld 4 c# asp.net exception mscorlib threadabortexception

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

Exception thrown: 'System.Threading.ThreadAbortException' in mscorlib.dll
Run Code Online (Sandbox Code Playgroud)

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

Response.Redirect("~/UI/Home.aspx");
Run Code Online (Sandbox Code Playgroud)

Response.Redirect("~/UI/Home.aspx", false);
Context.ApplicationInstance.CompleteRequest();
Run Code Online (Sandbox Code Playgroud)

但是我仍然遇到同样的问题。我使用调试器运行了代码,一切都成功执行,直到我调用 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.";
        }
    }
Run Code Online (Sandbox Code Playgroud)

对于为什么会发生这种情况有什么想法吗?

Joh*_* Wu 6

我过去见过这个问题。理论上,如果您使用此代码,则不会发生这种情况:

Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
Run Code Online (Sandbox Code Playgroud)

话虽如此,我有时仍然会得到这些,这真的很令人惊讶。我猜测有时会在存在活动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.
    }
}
Run Code Online (Sandbox Code Playgroud)