2017-02-20 94 views
0

在ASP.NET Web窗体中按钮的OnClick方法中,我调用了Response.Redirect()这会导致系统中止该线程并显示错误消息:“抛出的异常:'mscorlib.dll中的'System.Threading.ThreadAbortException'使用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();.

的OnClick功能

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

为什么这可能发生的任何想法?

+1

'的Response.Redirect()'*真的不应该*给予'FALSE'参数时,抛出该异常... – David

+0

的可能的复制[为什么Response.Redirect的原因System.Threading.ThreadAbortException ?](http://stackoverflow.com/questions/2777105/why-response-redirect-causes-system-threading-threadabortexception) –

+0

@Am_I_Helpful非常类似的问题,但它没有解决方案。 –

回答

1

我以前见过这个问题。从理论上讲,如果您使用此代码,这是不应该的:

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

感谢您的回答!不幸的是,这似乎没有解决问题 - 它仍然只是重新加载登录页面。 –

0

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

感谢