0

在 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.";
        }
    }

关于为什么会发生这种情况的任何想法?

4

3 回答 3

5

我过去曾看到过这个问题。理论上,如果你使用这段代码,它不应该发生:

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.
    }
}
于 2017-02-21T04:08:37.777 回答
2

我解决这个使用

Response.Redirect(.....)
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.    

参考:Excel 文件下载期间如何避免 Response.End()“线程被中止”异常

于 2018-05-10T15:58:04.140 回答
1

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

谢谢

于 2017-02-21T14:40:20.627 回答