c# - Response.End() 错误

标签 c# asp.net html thread-safety

我一直在尝试使用 Response.End() 方法,但不断收到此错误;

[System.Threading.ThreadAbortException] = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}

我用谷歌搜索了这个,从我所看到的有两种解决方案,一种是使用 HttpContext.Current.ApplicationInstance.CompleteRequest();另一种是只捕获异常而不执行任何操作。

首先,“捕获但不执行任何操作”似乎是一种非常“糟糕”的方法,我们当然应该实际处理异常或执行某些操作以使异常不会发生?这当然是个好习惯吗?我不希望我的代码充满大量的 try-catch。

另一种方法HttpContext.Current.ApplicationInstance.CompleteRequest();似乎不起作用。

这是我的代码片段:

Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "text/html");
Response.Write("Blocked IP");
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
return;

我想做的就是输出文本“阻止的 IP”,但使用 HttpContext.Current.ApplicationInstance.CompleteRequest();方法将 aspx 页面的其余部分打印在其下方,如下所示:

Blocked IP

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>

    </title></head>
    <body>
        <form method="post" action="Email.aspx" id="form1">
    <div class="aspNetHidden">
    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZIELtfylTwZMU8vGWe9UrhWClqN3i4rMTvAp8otze+6G" />
    </div>

        <div>

        </div>
        </form>
    </body>
    </html>

最佳答案

这是有意的。它旨在引发此异常,以便 asp.net 知道停止当前执行。

来自HttpResponse.End .

Calls to the End, Redirect, and Transfer methods throw a ThreadAbortException exception when the current response ends prematurely.

它适用于在 Page_Init 中调用 Reponse.End() 的情况,它不允许 ASP.NET 调用 Page_Load 以及页面生命周期中的其余事件。

关于c# - Response.End() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12518967/

相关文章:

html - 使用LoadRunner录制脚本

html - 将 font-awesome 链接到 amp 页面

c# - 资源位图文件 - 不包含属性定义

c# - .Net 5 - Asp.Net 仍然没有 SynchronizationContext?

C#清除已关闭应用程序的托盘图标

asp.net - 一个存储库应该调用另一个存储库吗?或者存储库应该调用服务层吗?

Asp.Net GridView 删除 Html 样式

javascript - 第一次打开时加载所有图片的简单图库

c# - 从 BitArray 转换为字节

c# - linq选择日期之间的位置