2011年10月25日

[ASP.NET]Response與Postback

目前開發中的專案,有一項功能是使用者能針對資料進行申請下載,當使用者點選申請列表的下載按鈕或整批下載按鈕時,資料將匯出成EXCEL檔案,並供使用者作後續使用,而位於申請下載列表的資料則轉入已下載列表內,如下圖所示。

  • 下載EXCEL檔案的程式碼如下:
  • Response.Clear();                
    Response.WriteFile(physicPath + fileName);
    string httpHeader = "attachment;filename=backup.Xls";
    Response.ContentType = "application/vnd.ms-excel";
    Response.AppendHeader("Content-Disposition", httpHeader);
    Response.Flush();
    Response.End();
    
實際執行功能時,系統順利的顯示檔案下載視窗,但卻無法將申請下載列表內的資料,轉入已下載列表,搜尋網路上的資料,原因為:
當使用到 Response.End 方法時,會呼叫內部的Thread.Abort()方法,引發ThreadAbortException 的例外,導致網頁的執行停止,並略過 Response.End 以下的程式碼。詳細說明,可參考Response.End() Exceptions in ASP.NET
本案例的情況為,網頁雖有作postback,但遇到Response的相關操作,程式執行過程中的部分程序將會被略過或終止,轉為將檔案輸出至用戶端,使得網頁並未回傳至用戶端的瀏覽器。
  • 解決方式,大多建議開新視窗進行檔案下載,開新視窗作檔案下載之程式碼如下:
  • string newWin = "window.open('" + "WEBFileURL" + fileName + "');";
    ClientScript.RegisterStartupScript(this.GetType(), "pop", newWin, true);