如何解决response.end中的错误 [英] Howto resolve the error in response.end
问题描述
在我的项目中,我正在导出excel文件以查看一些数据.当我单击按钮时,它会引发如下错误(该错误在Response.End行中引发):
[System.Threading.ThreadAbortException] = {由于代码已优化或本机框架位于调用堆栈的顶部,因此无法评估表达式.}
这是代码:
Hi,
In my project I am exporting excel file to view some data''s. When I am clicking the button it throws an error as follows(The error is thrown in the line 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.}
Here is the Code:
public static void ExportDataTableToCSV(DataTable dataTable, string CSVFileName)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
System.Web.HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + CSVFileName + ".csv");
//Write a row for column names
foreach (DataColumn dataColumn in dataTable.Columns)
context.Response.Write(dataColumn.ColumnName + ",");
context.Response.Write(Environment.NewLine);
//Write one row for each DataRow
foreach (DataRow dataRow in dataTable.Rows)
{
for (int dataColumnCount = 0; dataColumnCount < dataTable.Columns.Count; dataColumnCount++)
context.Response.Write(dataRow[dataColumnCount].ToString() + ",");
context.Response.Write(Environment.NewLine);
}
response.End(); //Here I am getting the error
}
谁能帮我解决这个问题.
在此先感谢
}
Can anyone help me to solve this issue.
Thanks in Advance
推荐答案
我在^ ]网站-
原因:
I am quoting the cause and resolution from Microsoft Support[^] site -
CAUSE:
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.
This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.
解决方法:
RESOLUTION:
To work around this problem, use one of the following methods:
For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.
For Server.Transfer, use the Server.Execute method instead.
顺便说一句,我通过谷歌搜索找到了这个有用的链接,以获取您的错误消息.如果您需要更多讨论,可以始终使用 ^ ]
希望这会有所帮助!
By the way, I found this USEFUL link by Googling for your error message. If you need more discussion you can always use the Google search link[^]
Hope this helps!
这篇关于如何解决response.end中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!