如何避免在Excel文件下载过程中出现Response.End()“线程被中止”异常

时间:2023-01-25 21:00:00

I tried to convert my dataset into excel and download that excel .I got my required excel file.But System.Threading.ThreadAbortException was raised every excel download. How to resolve this issue ?.. Please help me...

我试着把我的数据集转换成excel,然后下载那个excel,我得到了我需要的excel文件。但System.Threading。每次下载excel都会引发ThreadAbortException。如何解决这个问题?请帮我…

I call this method in my aspx screen.There also same exception has thrown by this method.

我在aspx屏幕中调用这个方法。这个方法也抛出了相同的异常。

I call that public void ExportDataSet(DataSet ds) function in many aspx screens and also I am maintaining error logger method for exceptions which are raised at runtime right those exceptions are write into a .txt files. So that same exception is logged in all the aspx screen's txt files.I just want to avoid this exception throws from method declared class file to aspx. Simply i just want to handle this exception at my method declaration class file itself.

我在许多aspx屏幕上调用public void ExportDataSet(DataSet ds)函数,我还为在运行时引起的异常维护错误日志记录方法,这些异常被写入.txt文件中。因此,在所有aspx屏幕的txt文件中都记录了相同的异常。我只是想避免这个异常从方法声明的类文件抛出到aspx。我只想在方法声明类文件本身处理这个异常。

ASPX File Method call: excel.ExportDataSet(dsExcel);

ASPX文件方法调用:excel.ExportDataSet(dsExcel);

Method Definition:

方法定义:

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
   {                
   }
}

13 个解决方案

#1


124  

I researched online and saw that the Response.End() always throws an exception.

我在网上搜索了一下,发现Response.End()总是抛出一个异常。

Replace this: HttpContext.Current.Response.End();

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

With this:

用这个:

    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.
    HttpContext.Current.Response.End();

#2


8  

This helped me to handle Thread was being aborted exception,

这帮助我处理线程被中止的异常,

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);
     }
   }

if you use the following the following code instead of HttpContext.Current.Response.End() , you will get Server cannot append header after HTTP headers have been sent exception.

如果您使用以下代码而不是HttpContext.Current.Response.End(),您将会得到服务器不能在HTTP头被发送异常后追加头。

            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.SuppressContent = True;
            HttpContext.Current.ApplicationInstance.CompleteRequest();

Hope it helps

希望它能帮助

#3


4  

Looks to be the same question as:

看起来是同一个问题:

When an ASP.NET System.Web.HttpResponse.End() is called, the current thread is aborted?

当一个ASP。调用NET System.Web.HttpResponse.End(),终止当前线程?

So it's by design. You need to add a catch for that exception and gracefully "ignore" it.

所以它的设计。您需要为该异常添加一个捕获并优雅地“忽略”它。

#4


3  

Use a special catch block for the exception of the Response.End() method

对Response.End()方法的异常使用一个特殊的catch块

{
    ...
    context.Response.End(); //always throws an exception

}
catch (ThreadAbortException e)
{
    //this is special for the Response.end exception
}
catch (Exception e)
{
     context.Response.ContentType = "text/plain";
     context.Response.Write(e.Message);
}

Or just remove the Response.End() if your building a filehandler

或者,如果构建文件处理程序,只需删除Response.End()

#5


2  

Move the Response.End() to outside of the Try/Catch and Using blocks.

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

It's suppose to throw an Exception to bypass the rest of the request, you just weren't suppose to catch it.

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

bool endRequest = false;

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

if (endRequest)
    Resonse.End();

#6


1  

Just put the

只是把

Response.End();

within a finally block instead of within the try block.

在finally块中而不是在try块中。

This has worked for me!!!.

这对我起作用了!!

I had the following problematic (with the Exception) code structure

我有以下问题(除了例外)代码结构

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);
   Response.End();

   return;

 } 

 some_more_code...

 Reponse.Write(...);
 Response.End();

}
catch(Exception){
}
finally{}

and it throws the exception. I suspect the Exception is thrown where there is code / work to execute after response.End(); . In my case the extra code was just the return itself.

它抛出了一个例外。我怀疑在response.End()之后有代码/工作要执行时抛出异常;。在我的例子中,额外的代码只是返回本身。

When I just moved the response.End(); to the finally block (and left the return in its place - which causes skipping the rest of code in the try block and jumping to the finally block (not just exiting the containing function) ) the Exception ceased to take place.

当我移动response.End()时;对于finally块(并保留返回值),异常停止发生。

The following works OK:

以下作品好:

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);

   return;

 } 

 some_more_code...

 Reponse.Write(...);

}
catch(Exception){
}
finally{
    Response.End();
}

#7


1  

the error for Response.END(); is because you are using a asp update panel or any control that using javascript, try to use control native from asp or html without javascript or scriptmanager or scripting and try again

Response.END错误();是因为您正在使用一个asp更新面板或任何使用javascript的控件,试图使用来自asp或html的本地控件,而不使用javascript或scriptmanager或脚本,然后再试一次

#8


1  

I removed the linkbutton from the UpdatePanel and also commented the Response.End() Success!!!

我从UpdatePanel中删除了linkbutton,并评论了Response.End() Success!

#9


1  

This is not issue but this is by design. The root cause is described in Microsoft Support Page.

这不是问题,但这是设计出来的。根源在Microsoft Support页面中进行了描述。

The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

响应。End方法结束页面执行,并将执行转移到应用程序事件管道中的Application_EndRequest事件。响应之后的代码行。不执行结束。

The provided Solution is:

所提供的解决方案是:

For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event

为响应。最后,调用HttpContext.Current.ApplicationInstance。全等方法代替响应。结束对Application_EndRequest事件的代码执行

Here is the link: https://support.microsoft.com/en-us/help/312629/prb-threadabortexception-occurs-if-you-use-response-end--response-redi

下面是链接:https://support.microsoft.com/en-us/help/312629/prb-threadabortexception- occurrence -if-you-use-response-end- response-redi

#10


0  

I recommend this solution :

我推荐这个解决方案:

  1. Don't use response.End();

    不要使用response.End();

  2. Declare this global var : bool isFileDownLoad;

    声明此全局var: bool isFileDownLoad;

  3. Just after your (response.Write(sw.ToString());) set ==> isFileDownLoad = true;

    设置=> isFileDownLoad = true;

  4. Override your Render like :

    覆盖你的渲染:

    /// AEG : Very important to handle the thread aborted exception

    /// AEG:处理中止异常的线程非常重要

    override protected void Render(HtmlTextWriter w) { if (!isFileDownLoad) base.Render(w); }

    覆盖保护的void呈现(HtmlTextWriter w) {if (!isFileDownLoad) base.Render(w);}

#11


0  

flush the response to the client before response.end()

在response.end()之前刷新对客户端的响应

More about Response.Flush Method

更多的反应。冲洗方法

So use the below-mentioned code before response.End();

因此,在response.End()之前使用下面提到的代码;

response.Flush();  

#12


0  

For me only works

对我来说只

HttpContext.Current.ApplicationInstance.CompleteRequest().

HttpContext.Current.ApplicationInstance.CompleteRequest()。

https://*.com/a/21043051/1828356

https://*.com/a/21043051/1828356

#13


0  

I used all above changes but still I was getting same issue on my web application.

我使用了以上所有的修改,但是我的web应用程序仍然存在同样的问题。

Then I contacted my hosting provide & asked them to check if any software or antivirus blocking our files to transfer via HTTP. or ISP/network is not allowing file to transfer.

然后我联系了我的托管供应商并要求他们检查是否有任何软件或防病毒阻止我们的文件通过HTTP传输。或者ISP/网络不允许文件传输。

They checked server settings & bypass the "Data Center Shared Firewall" for my server & now our application is able to download the file.

他们检查了服务器设置并绕过了我的服务器的“数据中心共享防火墙”,现在我们的应用程序可以下载文件了。

Hope this answer will help someone.This is what worked for me

希望这个答案能对某些人有所帮助。这对我起了作用

#1


124  

I researched online and saw that the Response.End() always throws an exception.

我在网上搜索了一下,发现Response.End()总是抛出一个异常。

Replace this: HttpContext.Current.Response.End();

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

With this:

用这个:

    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.
    HttpContext.Current.Response.End();

#2


8  

This helped me to handle Thread was being aborted exception,

这帮助我处理线程被中止的异常,

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);
     }
   }

if you use the following the following code instead of HttpContext.Current.Response.End() , you will get Server cannot append header after HTTP headers have been sent exception.

如果您使用以下代码而不是HttpContext.Current.Response.End(),您将会得到服务器不能在HTTP头被发送异常后追加头。

            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.SuppressContent = True;
            HttpContext.Current.ApplicationInstance.CompleteRequest();

Hope it helps

希望它能帮助

#3


4  

Looks to be the same question as:

看起来是同一个问题:

When an ASP.NET System.Web.HttpResponse.End() is called, the current thread is aborted?

当一个ASP。调用NET System.Web.HttpResponse.End(),终止当前线程?

So it's by design. You need to add a catch for that exception and gracefully "ignore" it.

所以它的设计。您需要为该异常添加一个捕获并优雅地“忽略”它。

#4


3  

Use a special catch block for the exception of the Response.End() method

对Response.End()方法的异常使用一个特殊的catch块

{
    ...
    context.Response.End(); //always throws an exception

}
catch (ThreadAbortException e)
{
    //this is special for the Response.end exception
}
catch (Exception e)
{
     context.Response.ContentType = "text/plain";
     context.Response.Write(e.Message);
}

Or just remove the Response.End() if your building a filehandler

或者,如果构建文件处理程序,只需删除Response.End()

#5


2  

Move the Response.End() to outside of the Try/Catch and Using blocks.

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

It's suppose to throw an Exception to bypass the rest of the request, you just weren't suppose to catch it.

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

bool endRequest = false;

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

if (endRequest)
    Resonse.End();

#6


1  

Just put the

只是把

Response.End();

within a finally block instead of within the try block.

在finally块中而不是在try块中。

This has worked for me!!!.

这对我起作用了!!

I had the following problematic (with the Exception) code structure

我有以下问题(除了例外)代码结构

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);
   Response.End();

   return;

 } 

 some_more_code...

 Reponse.Write(...);
 Response.End();

}
catch(Exception){
}
finally{}

and it throws the exception. I suspect the Exception is thrown where there is code / work to execute after response.End(); . In my case the extra code was just the return itself.

它抛出了一个例外。我怀疑在response.End()之后有代码/工作要执行时抛出异常;。在我的例子中,额外的代码只是返回本身。

When I just moved the response.End(); to the finally block (and left the return in its place - which causes skipping the rest of code in the try block and jumping to the finally block (not just exiting the containing function) ) the Exception ceased to take place.

当我移动response.End()时;对于finally块(并保留返回值),异常停止发生。

The following works OK:

以下作品好:

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);

   return;

 } 

 some_more_code...

 Reponse.Write(...);

}
catch(Exception){
}
finally{
    Response.End();
}

#7


1  

the error for Response.END(); is because you are using a asp update panel or any control that using javascript, try to use control native from asp or html without javascript or scriptmanager or scripting and try again

Response.END错误();是因为您正在使用一个asp更新面板或任何使用javascript的控件,试图使用来自asp或html的本地控件,而不使用javascript或scriptmanager或脚本,然后再试一次

#8


1  

I removed the linkbutton from the UpdatePanel and also commented the Response.End() Success!!!

我从UpdatePanel中删除了linkbutton,并评论了Response.End() Success!

#9


1  

This is not issue but this is by design. The root cause is described in Microsoft Support Page.

这不是问题,但这是设计出来的。根源在Microsoft Support页面中进行了描述。

The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

响应。End方法结束页面执行,并将执行转移到应用程序事件管道中的Application_EndRequest事件。响应之后的代码行。不执行结束。

The provided Solution is:

所提供的解决方案是:

For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event

为响应。最后,调用HttpContext.Current.ApplicationInstance。全等方法代替响应。结束对Application_EndRequest事件的代码执行

Here is the link: https://support.microsoft.com/en-us/help/312629/prb-threadabortexception-occurs-if-you-use-response-end--response-redi

下面是链接:https://support.microsoft.com/en-us/help/312629/prb-threadabortexception- occurrence -if-you-use-response-end- response-redi

#10


0  

I recommend this solution :

我推荐这个解决方案:

  1. Don't use response.End();

    不要使用response.End();

  2. Declare this global var : bool isFileDownLoad;

    声明此全局var: bool isFileDownLoad;

  3. Just after your (response.Write(sw.ToString());) set ==> isFileDownLoad = true;

    设置=> isFileDownLoad = true;

  4. Override your Render like :

    覆盖你的渲染:

    /// AEG : Very important to handle the thread aborted exception

    /// AEG:处理中止异常的线程非常重要

    override protected void Render(HtmlTextWriter w) { if (!isFileDownLoad) base.Render(w); }

    覆盖保护的void呈现(HtmlTextWriter w) {if (!isFileDownLoad) base.Render(w);}

#11


0  

flush the response to the client before response.end()

在response.end()之前刷新对客户端的响应

More about Response.Flush Method

更多的反应。冲洗方法

So use the below-mentioned code before response.End();

因此,在response.End()之前使用下面提到的代码;

response.Flush();  

#12


0  

For me only works

对我来说只

HttpContext.Current.ApplicationInstance.CompleteRequest().

HttpContext.Current.ApplicationInstance.CompleteRequest()。

https://*.com/a/21043051/1828356

https://*.com/a/21043051/1828356

#13


0  

I used all above changes but still I was getting same issue on my web application.

我使用了以上所有的修改,但是我的web应用程序仍然存在同样的问题。

Then I contacted my hosting provide & asked them to check if any software or antivirus blocking our files to transfer via HTTP. or ISP/network is not allowing file to transfer.

然后我联系了我的托管供应商并要求他们检查是否有任何软件或防病毒阻止我们的文件通过HTTP传输。或者ISP/网络不允许文件传输。

They checked server settings & bypass the "Data Center Shared Firewall" for my server & now our application is able to download the file.

他们检查了服务器设置并绕过了我的服务器的“数据中心共享防火墙”,现在我们的应用程序可以下载文件了。

Hope this answer will help someone.This is what worked for me

希望这个答案能对某些人有所帮助。这对我起了作用