我正在使用以下代码在asp.net中下载文件
public void DownloadFile(String fileName, String msg)
{
if (String.IsNullOrEmpty(fileName))
{
fileName = "Document.txt";
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(ms))
{
sw.Write(msg);
sw.Flush();
ms.Position = 0;
using (Stream download = ms)
{
byte[] buffer = new Byte[ms.Length];
if (HttpContext.Current.Response.IsClientConnected)
{
int length = 0;
length = download.Read(buffer, 0, buffer.Length);
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
}
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
}
}
我在“HttpContext.Current.Response.End();”中遇到异常 的 HttpContext.Current.Response.End();无法评估表达式,因为代码已优化或本机框架位于调用堆栈之上。
我需要在代码中更改什么?我做错了。
答案 0 :(得分:0)
请参阅Link帮助您:
如果需要,使用try-catch语句来捕获异常
try
{
}
catch (System.Threading.ThreadAbortException ex)
{
}
For Response.End : Invoke 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 endResponse parameter to suppress the internal call to Response.End
// code that follows Response.Redirect is executed
Response.Redirect ("mynextpage.aspx", false);
For Server.Transfer : Use Server.Execute method to bypass abort. When Server.Execute is used, execution of code happens on the new page, post which the control returns to the initial page, just after where it was called
<强>限制/结论:强>
这是按照设计的。此异常对Web应用程序性能有不良影响,这就是正确处理方案很重要的原因。