gpt4 book ai didi

c# - 如何避免在 Excel 文件下载期间出现 Response.End() "Thread was being aborted"异常

转载 作者:IT王子 更新时间:2023-10-29 03:37:41 27 4
gpt4 key购买 nike

我尝试将我的数据集转换为 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 = ex.Message.ToString();
EsHelper.EsADLogger("HOQCMgmt.aspx ibtnExcelAll_Click()", ex.Message.ToString());
}
finally
{
}
}

最佳答案

我在网上进行了研究,发现 Response.End() 总是抛出异常。

替换为:HttpContext.Current.Response.End();

有了这个:

HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.

关于c# - 如何避免在 Excel 文件下载期间出现 Response.End() "Thread was being aborted"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20988445/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com