關於 Response.end() 一點想法

使用  Response.end() 會產生ThreadAbortException 的異常。 試着要解決該問題。

我產生該問題的場景是: GridView  導出爲Excel  涉及代碼爲:

 StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            Page page = new Page();
            HtmlForm form = new HtmlForm();

            ctl.EnableViewState = false;

            page.EnableEventValidation = false;

            page.DesignerInitialize();

            page.Controls.Add(form);
            form.Controls.Add(ctl);

            page.RenderControl(htw);

            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8) + ".xls");
            Response.Charset = "UTF-8";
            Response.ContentEncoding = Encoding.Default;
            Response.Write("<html>");
            Response.Write("<head><meta http-equiv=/"Content-Type/" contect=/"text/html/";charset=gb2312/"></head>");
            Response.Write(sb.ToString());
            Response.Write("</html>");
            Response.End();

注意使用該方法 GridView 不能隱藏, 否則form.Controls.Add(ctl);爲空字符

不管如何,都會產生該異常。

在網上找了好幾個小時,都沒有解決該問題, 只能用try{}catch{}將導出代碼包起來。算是把問題處理了, 但這樣處理畢竟不盡人意。

 

網上有說: 用HttpContext.Current.ApplicationInstance.CompleteRequest();取代Response.End(); 但是沒有用。(該方法不會終止一個請求)

具體解釋爲:

           “利用HttpModule通過調用HttpApplication.CompleteRequest()方法實現當滿足某一個條件時終止此次的HTTP請求。需要注意的是,即使調用了HttpApplication.CompleteRequest()方法終止了一個HTTP請求,ASP.NETFramework仍然會觸發HttpApplication後面的這3個事件:EndRequest事件、PreSendRequestHeaders事件、PreSendRequestContent事件。”

 

        而且在end()更改的頁面提示信息無法發送到客戶端。

 

困惑呀!  只能把該問題記下來,找機會在解決!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章