ASP.NET頁面跳轉Response.Redirect拋出異常

來源:互聯網
上載者:User

在ASP.NET按鈕響應中跳轉到其他的頁面,會拋出異常’Thread was being aborted’,如下代碼

try
{
    string redirectUrl = "~/Default.aspx";
    Response.Redirect(redirectUrl);
}
catch (System.Exception ex)
{
}

 

在微軟的網站上找到有對應的問題:

ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

 

按照微軟的解決方案,只要調用Response.Redirect的重載函數Response.Redirect(String url, bool endResponse),其中endResponse傳入false就可以了

Response.Redirect(redirectUrl,false);
我看了一下ASP.NET的原始碼,其中會拋出一個異常,下面是代碼:
     /// <devdoc>      ///    <para>Redirects a client to a new URL.</para>      /// </devdoc>        public void Redirect(String url, bool endResponse) {             if (url == null)                throw new ArgumentNullException("url");            if (url.IndexOf('\n') >= 0)                 throw new ArgumentException(SR.GetString(SR.Cannot_redirect_to_newline));             if (_headersWritten)                 throw new HttpException(SR.GetString(SR.Cannot_redirect_after_headers_sent));             Page page = _context.Handler as Page;            if ((page != null) && page.IsCallback) {                throw new ApplicationException(SR.GetString(SR.Redirect_not_allowed_in_callback));            }             url = ApplyRedirectQueryStringIfRequired(url);              url = ApplyAppPathModifier(url);             url = ConvertToFullyQualifiedRedirectUrlIfRequired(url);            url = UrlEncodeRedirect(url);             Clear();             // If it's a Page and SmartNavigation is on, return a short script             // to perform the redirect instead of returning a 302 (bugs ASURT 82331/86782)#pragma warning disable 0618    // To avoid SmartNavigation deprecation warning             if (page != null && page.IsPostBack && page.SmartNavigation && (Request["__smartNavPostBack"] ==        "true")) {#pragma warning restore 0618                Write("<BODY><ASP_SMARTNAV_RDIR url=\"");                Write(HttpUtility.HtmlEncode(url));                 Write("\"></ASP_SMARTNAV_RDIR>");                 Write("</BODY>");             }            else {                 this.StatusCode = 302;                RedirectLocation = url;                Write("<html><head><title>Object moved</title></head><body>\r\n");                Write("<h2>Object moved to <a href=\"" + HttpUtility.HtmlAttributeEncode(url) + "\">here</a>.</h2>\r\n");                 Write("</body></html>\r\n");            }              _isRequestBeingRedirected = true;             if (endResponse)                End();        }        /*         * Cancelles handler processing of the current request          * throws special [non-]exception uncatchable by the user code         * to tell application to stop module execution.          */         /// <devdoc>         ///    <para>Sends all currently buffered output to the client then closes the        ///       socket connection.</para>        /// </devdoc>        public void End() {             if (_context.IsInCancellablePeriod) {                 InternalSecurityPermissions.ControlThread.Assert();                 Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));            }             else {                // when cannot abort execution, flush and supress further output                if (!_flushing) { // ignore Reponse.End while flushing (in OnPreSendHeaders)                    Flush();                     _ended = true;                     if (_context.ApplicationInstance != null) {                         _context.ApplicationInstance.CompleteRequest();                    }                 }            }        }

上面的紅色代碼Thread.CurrentThread.Abort裡面就會拋出異常,只要執行還在容許Cancel的時間都會拋異常。

當然什麼時候會不容許呢(_context.IsInCancellablePeriod為false),我倒是沒看了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.