如何避免Response.End()"线程被中止"Excel文件下载期间出现异常

use*_*957 89 c# asp.net

我试图将我的数据集转换为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
   {                
   }
}
Run Code Online (Sandbox Code Playgroud)

小智 174

我在网上研究过,看到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.
Run Code Online (Sandbox Code Playgroud)

  • 不.对我不起作用.其实看看答案.如果`Response.End()`确实***不工作,为什么建议的答案在最后一行也有`Response.End()`?相反@Binny(下面)的答案有帮助! (3认同)
  • 这解决了我的问题。谢谢 (2认同)
  • 哇天赐良机。它为我节省了使用 WinDbg 进行调试的时间。就我而言,如果 ThreadAbortException 太多,我的 w3wp.exe 就会崩溃 (2认同)
  • 根据 https://docs.microsoft.com/en-us/dotnet/api/system.web.httpresponse.end Request.End 上的文档,仅支持向后兼容。推荐使用 CompleteRequest 作为替代 (2认同)

Bin*_*nny 11

这有助于我处理Thread was being aborted异常,

try
{
   //Write HTTP output
    HttpContext.Current.Response.Write(Data);
}  
catch (Exception exc) {}
finally {
   try 
    {
      //stop processing the script and return the current result
      HttpContext.Current.Response.End();
     } 
   catch (Exception ex) {} 
   finally {
        //Sends the response buffer
        HttpContext.Current.Response.Flush();
        // Prevents any other content from being sent to the browser
        HttpContext.Current.Response.SuppressContent = true;
        //Directs the thread to finish, bypassing additional processing
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        //Suspends the current thread
        Thread.Sleep(1);
     }
   }
Run Code Online (Sandbox Code Playgroud)

如果您使用以下代码代替HttpContext.Current.Response.End(),则会出现Server cannot append header after HTTP headers have been sent异常.

            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.SuppressContent = True;
            HttpContext.Current.ApplicationInstance.CompleteRequest();
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你

  • 多么可怕的解决方案 (3认同)

Ste*_*eve 5

将 Response.End() 移至 Try/Catch 和 using 块的外部。

它应该抛出一个异常来绕过请求的其余部分,你只是不应该捕获它。

bool endRequest = false;

try
{
    .. do stuff
    endRequest = true;
}
catch {}

if (endRequest)
    Resonse.End();
Run Code Online (Sandbox Code Playgroud)


rob*_*ick 4

看起来与以下问题相同:

当调用 ASP.NET System.Web.HttpResponse.End() 时,当前线程被中止?

所以这是设计使然。您需要为该异常添加捕获并优雅地“忽略”它。