try catch中使用Response.End()

A.

如果使用 Response.End、Response.Redirect 或 Server.Transfer 方法,将出现 ThreadAbortException 异常。异常内容:由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值

您可以使用 try-catch 语句捕获此异常。

Response.End 方法终止页的执行,并将此执行切换到应用程序的事件管线中的 Application_EndRequest 事件。不执行 Response.End 后面的代码行。

此问题出现在 Response.Redirect 和 Server.Transfer 方法中,因为这两种方法均在内部调用 Response.End

解决方案 :
• 对于 Response.End,调用 HttpContext.Current.ApplicationInstance.CompleteRequest 方法而不是 Response.End 以跳过 Application_EndRequest 事件的代码执行。
 对于 Response.Redirect,请使用重载 Response.Redirect(String url, bool endResponse),该重载对 endResponse 参数传递 false 以取消对 Response.End 的内部调用。例如:
Response.Redirect ("nextpage.aspx", false);

B.

在调用Response.End()时,会执行Thread.CurrentThread.Abort()操作。

如果将Response.End()放在try...catch中,catch会捕捉Thread.CurrentThread.Abort()产生的异常System.Threading.ThreadAbortException。

解决方法(任选一个):

  1. 在catch中排除ThreadAbortException异常,示例代码如下:

    try{ Response.End();}catch (System.Threading.ThreadAbortException){}catch (Exception ex){ Response.Write(ex);}

  2. 用Context.ApplicationInstance.CompleteRequest()结束当前请求,代码如下:

    protected void Page_Load(object sender, EventArgs e){ try { Response.Write("Hello world!"); this.Page.Visible = false; Context.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { Response.Write(ex); }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值