[英]System.Threading.ThreadAbortException on generic redirection
我正在一個ASP.Net
項目中,我們有一個centralized redirection method
。 但有時會引發異常:
System.Threading.ThreadAbortException
主要問題在於,通常在調用SBA.Redirect("AnotherPage.aspx")
之后代碼執行不會停止,並且以下代碼仍在執行。
我的通用功能:
public static class SBA
{
public static void Redirect(string Url)
{
try
{
HttpContext.Current.Response.Redirect(Url, false);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
if (ex.GetType() != typeof(System.Threading.ThreadAbortException))
{
throw;
}
}
}
}
Redirect
專門引發ThreadAbortException
以便停止運行以下任何代碼。
您正在處理ThreadAbortException
。
因此,下面的代碼正在運行。
如果您不希望運行以下代碼,請不要處理ThreadAbortException
。
只需進行以下調用即可進行重定向:
HttpContext.Current.Response.Redirect(Url);
您的代碼有兩個問題:
您使用Redirect
的重載,通過為endResponse
參數提供false
來決定不結束響應。 因此,重定向后的代碼將執行。
您嘗試捕獲ThreadAbortException
。 如上所述使用正常重定向時,將引發此異常。 這不是錯誤情況,而只是ASP.NET確保當前請求正確終止的一種方式。 您可以捕獲異常,但是該異常會在catch塊的末尾重新拋出,因此您的catch塊將無用。
由於重定向時會引發異常,因此您應注意注釋中解釋的以下內容:
void HandleRequest() {
try {
Response.Redirect(" ... url ... ");
}
catch (Exception) {
// Code here will execute after the redirect.
}
}
為了避免出現問題,最好的辦法是在catch處理程序中捕獲更具體的異常類型,或者至少不要在處理程序中執行任何會干擾重定向的操作(例如,寫入響應流)。
我使用以下代碼保護了redirection
。 工作正常
public static class SBA
{
public static void Redirect(string Url)
{
try
{
//redirect only when 'IsRequestBeingRedirected' is false
if (!HttpContext.Current.Response.IsRequestBeingRedirected)
{
Uri uri = null;
bool isUriValid = Uri.TryCreate(Url, UriKind.RelativeOrAbsolute, out uri);
if (!isUriValid)
{
throw new SecurityException("Invalid uri " + Url);
}
//Below check is not required but checked
//to make obsolate security check
if (uri.OriginalString == null)
{
throw new SecurityException("Invalid uri " + Url);
}
// check if host is from configured trusted host list
if (uri.IsAbsoluteUri)
{
var tempAppSetting = ConfigBLL.GetAppSetting(AppSettingSectionType.OtherSetting).Other;
if (!tempAppSetting.RedirectTrustedUrls.Contains(uri.Host))
{
throw new SecurityException("Untrusted url redirection detected. Can not redirect.");
}
}
var tempUrl = uri.OriginalString;
//Few more logical check
HttpContext.Current.Response.Redirect(tempUrl, true);
}
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
if (ex.GetType() != typeof(System.Threading.ThreadAbortException))
{
throw;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.