2013-10-06 57 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