c# - "Exception thrown: ' System.Threading.ThreadAbortException ' in mscorlib.dll"使用 Response.Redirect() 时

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

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

最佳答案

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

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

话虽如此,我有时还是会得到这些,这真是令人惊讶。我猜它有时会出现在事件的 finally block 中,以指示代码开始清理自己,尽管对你来说似乎并非如此。

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

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.
    }
}

关于c# - "Exception thrown: ' System.Threading.ThreadAbortException ' in mscorlib.dll"使用 Response.Redirect() 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42350624/

相关文章:

c# - 如何使用 PostSharp 属性注入(inject)属性?

c# - 模块化单体中的跨模块通信

c# - 对基类的派生类进行序列化和反序列化

c# - 在 Azure Functions 2.0 中使用 EasyAuth 时,依赖项将 ClaimsPrincipal 注入(inject) DbContext

asp.net - 启用自定义错误时,Elmah 不会触发

asp.net - 有没有办法控制ASP.NET中发送的邮件?

asp.net - .Net Core Cookie 身份验证在 IIS 中托管时不起作用

c# - 访问/写入 EventLog 时出现问题

java - 不考虑 Mapper 和 Reducer 接口(interface)

Java 索引异常