2017-02-20 97 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

這竟然是我已被重定向回來,如果會議不包含在目標頁面的特定元素引起的問題,在這種情況下它都沒有!異常仍然被拋出,但不再導致可見的問題。

感謝