2013-10-06 58 views
0

我让用户使用下面的代码下载文件。它工作正常,但也产生误差和源用于误差是Response.End();由Response.End()生成的异常

错误消息无法对表达式进行,因为代码被优化或天然帧是在呼叫stack.`

下面的顶是我的代码。我该如何处理这个错误,并且这个错误并没有释放我的资源,这可能导致不需要的内存使用。

我用这个用于asp.net webform应用程序。

try 
    { 
     string fileName = Request["file_ID"]; 
     string path = Server.MapPath("~/App_Data/uploads/"+fileName); 


     //string = Server.MapPath(strRequest); 
     System.IO.FileInfo file = new System.IO.FileInfo(path); 
     if (file.Exists) 
     { 
      Response.Clear(); 
      Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
      Response.AddHeader("Content-Length", file.Length.ToString()); 
      Response.ContentType = "application/"+file.Extension; 
      Response.WriteFile(file.FullName); 
      Response.End(); 

      // System.Threading.Thread.Sleep(2000); 
      // Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "alert('aa')", true); 

     } 
     else 
     { 
      //Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "myWindow.close();", true); 
     } 
    } 


    catch (Exception rt) 
    { 
     Response.Write(rt.Message); 
    } 
} 

我一直在寻找这个解决办法,但我不知道我怎么能在我的代码实现它。

Unable to evaluate expression... on web page

UPDATE:

其实我是想用户下载文件,并使用它的后面在代码注释现在脚本代码接近相同。

所以我不知道如何更好地优化这段代码来处理由respond.end语句生成的异常。

我试过使用Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "myWindow.close();", true);,但它也不起作用。

感谢

回答

1

对方回答似乎是说,你可以不使用作为到Response.End这是不必要的,或添加渔获量,你有你的当前抓

问题链接another question ThreadAbortException这表明,添加以下:

// Sends the response buffer 
Response.Flush() 

// Prevents any other content from being sent to the browser 
Response.SuppressContent = TrueResponse.SuppressContent = True 
+0

我认为用户提出更好的方法使用建议,还可以使用ashx的文件,这个的话,我不需要对弥合窗口工作。对于任何异常错误,我会将它们重定向到错误页面。 – Learning

1

使用HttpContext.Current.ApplicationInstance.CompleteRequest

或尝试像

Response.OutputStream.Flush() 
Response.OutputStream.Close() 
Response.Flush() 
Response.End() 

阅读Is Response.End() considered harmful?

+0

我认为更好的方法使用用户建议的建议,也可以使用.ashx文件,然后我不需要关闭窗口。对于任何异常错误,我会将它们重定向到错误页面。 – Learning