2017年12月21日 星期四

Response.End 的Exception -Thread was being aborted

下載檔案發生 exception
Thread was being aborted
本來看到有人說不執行既可
但用Try/catch 包住不執行ThreadAbortException 的例外,一樣會有問題
且違反例外原則

參考了黑大及傑哥的文件後,將 Response.End()拿掉,換成HttpContext.Current.ApplicationInstance.CompleteRequest();
解決;感謝。



 public void DownloadFile( string Files)
    {
        try
        {
            string FileName = Path.GetExtension(Files);
            System.Web.HttpContext.Current.Response.Clear(); //清除buffer
            System.Web.HttpContext.Current.Response.ClearHeaders(); //清除 buffer 表頭
            System.Web.HttpContext.Current.Response.Buffer = false;
            System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
            // 檔案類型還有下列幾種"application/pdf"、"application/vnd.ms-excel"、"text/xml"、"text/HTML"、"image/JPEG"、"image/GIF"
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
            // 考慮 utf-8 檔名問題,以 out_file 設定另存的檔名
            //System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", attach.Length.ToString()); //表頭加入檔案大小
            //System.Web.HttpContext.Current.Response.BinaryWrite(attach);
            System.Web.HttpContext.Current.Response.WriteFile(Files);
            // 將檔案輸出
            System.Web.HttpContext.Current.Response.Flush();
            // 強制 Flush buffer 內容
            //System.Web.HttpContext.Current.Response.End();
          HttpContext.Current.ApplicationInstance.CompleteRequest();
        }

        catch (ThreadAbortException ex)
        { }
        catch (Exception ex)
        {
            throw ex;
        }

    }

參考:
http://blog.darkthread.net/post-2007-03-08-threadabortexception-when-response-end.aspx
https://dotblogs.com.tw/jeffyang/2017/06/14/214252