ASP.NET页面跳转Response.Redirect抛出异常

在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),我倒是没看了。
posted @ 2010-11-22 20:44  Quincy  阅读(3223)  评论(1编辑  收藏  举报