这篇知识库文章说,ASP.NET Response.End()中止了一个帖子.
反射器显示它看起来像这样:
public void End()
{
if (this._context.IsInCancellablePeriod)
{
InternalSecurityPermissions.ControlThread.Assert();
Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
}
else if (!this._flushing)
{
this.Flush();
this._ended = true;
if (this._context.ApplicationInstance != null)
{
this._context.ApplicationInstance.CompleteRequest();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎很苛刻.正如知识库文章所说,以下应用程序中的任何代码Response.End()都不会被执行,这违反了最不惊讶的原则.它几乎就像Application.Exit()在WinForms应用程序中.造成线程终止异常Response.End()不开捕,所以代码周围的try...... finally不会满足.
这让我想知道我是否应该总是避免Response.End().
任何人都可以建议,我什么时候应该使用Response.End(),何时Response.Close()何地HttpContext.Current.ApplicationInstance.CompleteRequest()?
参考:Rick Strahl的博客文章.
根据我收到的输入,我的回答是,是的,Response.End是有害的,但在某些有限的情况下它是有用的.
Response.End()作为一个不可捕获抛出,立即终止HttpResponse在特殊的条件.在调试过程中也很有用. 避免Response.End()完成常规反应.Response.Close()立即关闭与客户端的连接.根据此MSDN博客文章,此方法不适用于正常的HTTP请求处理. 你不太可能有充分的理由来调用这种方法.我试图将我的数据集转换为excel并下载excel.我得到了我所需的excel文件.但每次excel下载都会引发System.Threading.ThreadAbortException.如何解决这个问题?请帮帮我...
我在我的aspx屏幕中调用此方法.此方法也引发了同样的异常.
我在许多aspx屏幕中调用public void ExportDataSet(DataSet ds)函数,并且我正在为运行时引发的异常维护错误记录器方法,将这些异常写入.txt文件.所以在所有aspx屏幕的txt文件中记录了相同的异常.我只想避免从方法声明的类文件抛出到aspx的异常抛出.我只是想在我的方法声明类文件本身处理这个异常.
ASPX文件方法调用:excel.ExportDataSet(dsExcel);
方法定义:
public void ExportDataSet(DataSet ds)
{
try
{
string filename = "ExcelFile.xls";
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
GridView dg = new GridView();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
// response.Write(style);
response.Write(sw.ToString());
response.End(); // Exception was Raised at here
}
}
}
catch (Exception ex)
{
string Err = …Run Code Online (Sandbox Code Playgroud)