2010-07-09 54 views
2

我知道(現在)Response.Redirect()和Response.End()拋出一個ThreadAbortException作爲一種消耗當前處理線程的昂貴方式來模擬ASP Classic的行爲Response.End()和Response.Redirect方法。Response.Redirect()ThreadAbortException間歇性冒泡過高

但是,

在我們的應用程序中似乎間歇性地發現異常泡沫太高。例如,我們有一個從客戶端javascript調用的頁面返回一個小字符串以顯示在頁面中。

protected void Page_Load(object sender, EventArgs e) 
{ 
     // Work out some stuff. 
     Response.Write(stuff); 
     Response.End(); 
} 

這通常工作,但有些時候,我們得到的異常向上冒泡到UI層,並得到在頁面上顯示的異常文本的一部分。

同樣地,其他地方有:

// check the login is still valid: 
if(!loggedin) { 
    Response.Redirect("login.aspx"); 
} 

在某些情況下,用戶會被重定向到login.aspx的,在其他國家,用戶得到的ASP.NET錯誤頁和堆棧轉儲(因爲如何我們的開發服務器已配置)。

即,在某些情況下,response.redirect一直拋出一個異常,直到INSTEAD做重定向。爲什麼?我們如何阻止這一點?

回答

1

您是否嘗試重載默認的重定向方法,而不是結束響應?

if(!loggedin) { 
    Response.Redirect("login.aspx", false); 
} 
+0

通過一些研究解決了什麼是正確的做法,但是仍然想了解爲什麼有時它會引發異常並且其他異常工作。 – THEMike 2010-07-09 15:31:05

+0

爲什麼使用Response.Write()將文本寫入頁面呢?這不是推薦的方法 - 它比ASP.NET更經典的ASP。 – 2010-07-09 16:48:43

1

您可以使用以下最佳實踐代碼代替,as explained by this answer防止異常在首位發生的事情:

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

但這不保留我的查詢字符串。它在頁面重定向時被刪除 – Happy 2018-02-22 11:26:11

0

因爲我一直在尋找的答案,這個問題也是,我我張貼到我什麼接縫的完整解決方案,圍捕上面的兩個答案:

public static void Redirect(this TemplateControl control, bool ignoreIfInvisible = true) 
{ 
    Page page = control.Page; 
    if (!ignoreIfInvisible || page.Visible) 
    { 
    // Sets the page for redirect, but does not abort. 
    page.Response.Redirect(url, false); 
    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline 
    // chain of execution and directly execute the EndRequest event. 
    HttpContext.Current.ApplicationInstance.CompleteRequest(); 

    // By setting this to false, we flag that a redirect is set, 
    // and to not render the page contents. 
    page.Visible = false; 
    } 
} 

來源: http://www.codeproject.com/Tips/561490/ASP-NET-Response-Redirect-without-ThreadAbortExcep