使用Response.Redirect()时获取线程中止exception

我在更新面板下的页面中编写了以下代码。

protected void myGrid_RowCommand(object sender, GridViewCommandEventArgs e) { try { if (e.CommandName =="EditNames") { long lSelectedName = Convert.ToInt64(e.CommandArgument); Session["SelectedItem"] = lSelectedName; Response.Redirect("EditItem.aspx"); } else if (e.CommandName =="DeleteNames") { long lSelectedName = Convert.ToInt64(e.CommandArgument); ValidName.DeleteItem(lSelectedName); ScriptManager.RegisterStartupScript(this, GetType(), "Key", "alert('Name deleted sucessfully')", true); } } catch (System.Threading.ThreadAbortException) { } catch (Exception ex) { Error handling code... } } 

在这里,我在重定向时遇到Thread Abort Exception。 但是,我通过使用error handling程序System.Threading.ThreadAbortException解决了它。

但我不确定为什么在重定向时出现错误。 即使我解决了这个问题,我想知道我编码的方式是否有任何错误,或者有任何方法可以阻止错误触发。

给你的意见……

请注意,该页面位于AJAX UPDATE PANEL下。

即使我解决了这个问题,我想知道我编码的方式是否有任何错误

没错,你做得很好。

此错误是预期的。 抛出它是因为重定向时服务器线程实际上已中止。 从MSDN文档 :

如果为endResponse参数指定true,则此方法为原始请求调用End方法,该方法在完成时抛出ThreadAbortExceptionexception。

以及您正在使用的重载文档

重定向调用End,在完成时抛出ThreadAbortExceptionexception。

请阅读这篇文章 – http://blogs.msdn.com/b/tmarq/archive/2009/06/25/correct-use-of-system-web-httpresponse-redirect.aspx

而不是结束请求,最好通过调用Context.ApplicationInstance.CompleteRequest()来绕过请求执行管道。

所以你的代码看起来像这样:

 Response.Redirect("TargetPage", false); //write redirect Context.ApplicationInstance.CompleteRequest(); // end response 

发生这种情况是因为您在try / catch块内重定向。 不要这样做。

在重定向方法中提及false就足够了,比如Response.Redirect(“TargetPage”,false);