首页 > 技术文章 > 在try...catch语句中执行Response.End()后如何停止执行catch语句中的内容

wintalen 2014-07-21 18:18 原文

在调用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);
    }
}

推荐阅读