我试图将我的数据集转换为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)
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)
希望能帮助到你
将 Response.End() 移至 Try/Catch 和 using 块的外部。
它应该抛出一个异常来绕过请求的其余部分,你只是不应该捕获它。
bool endRequest = false;
try
{
.. do stuff
endRequest = true;
}
catch {}
if (endRequest)
Resonse.End();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
128969 次 |
| 最近记录: |