Response.Redirect caused "cannot redirect after HTTP headers are sent"

Source: Internet
Author: User
Tags bool flush httpcontext throw exception visual studio

After the blog was switched back to i.cnblogs.com, a large number of error messages were found in the log that could not be redirected after sending HTTP headers (cannot redirect after HTTP headers have been).

Check the code to see that the problem is triggered by the following code:

IHttpHandler Ihttphandlerfactory.gethandler (HttpContext context, string RequestType, String url, String pathtranslated )
{context
    . Response.Redirect ("http://i.cnblogs.com/" + context 
        .) Request.RawUrl.Substring (context. Request.RawUrl.LastIndexOf ("/") + 1));
    
    Follow-up also has a context. Response.Redirect code
    //...
    Return pageparser.getcompiledpageinstance (Newurl, path, context);
}

"Cannot redirect after sending HTTP headers" The problem comes from Response.Redirect and Response.Redirect.

The workaround is simple: return immediately after Response.Redirect.

IHttpHandler Ihttphandlerfactory.gethandler (HttpContext context, string RequestType, String url, String pathtranslated )
{context
    . Response.Redirect ("http://i.cnblogs.com/" + context 
        .) Request.RawUrl.Substring (context. Request.RawUrl.LastIndexOf ("/") + 1));
    return null;
    //...    
}

Why didn't you add a return null before? The code after Response.Redirect is not executed because it was previously assumed that Response.Redirect would end the current request.

Now the brutal reality shows that this is not exactly the case, what is the truth behind the question? Let's take a dip.

Since Microsoft exposes the source code of the. NET framework, you can now download the source code directly from Visual Studio without looking at the Reflactor code.

. NET Framework Source code download link: http://referencesource.microsoft.com/download.html (related news: Microsoft has opened the source code for. NET 4.5.1)

Open Dotnetreferencesource\source\ndp.sln with Visual Studio, search HttpResponse.cs, and find the implementation code for Response.Redirect:

public void Redirect (String url)
{
    Redirect (URL, True, false);
}

The actual call is internal void Redirect (String URL, bool endresponse, BOOL permanent), and the value passed to Endresponse is true, why does the following code execute?

Further view the implementation code for the internal void Redirect () (omitting extraneous code):

internal void Redirect (String URL, bool endresponse, BOOL permanent) 
{
    //...
    
    Page page = _context. Handler as Page;
    if (page!= null) && page. Iscallback) {
        ///Throw exception
    }
    
    //... URL processing clear
    
    ();//clears all headers and content output from the buffer stream .
    
    //...
    This. StatusCode = permanent? 301:302; REDIRECT Operation
    //...
    _isrequestbeingredirected = true; 
    
    var redirectinghandler = redirecting;
    if (Redirectinghandler!= null) {
        Redirectinghandler (this, eventargs.empty);
    }
    
    if (endresponse)
        end ();//ending current request
}

As you can see from the code above, we're looking for the truth. In the end () method, continue to see the implementation code for Httpresponse.end ():

public void End () {
    if (_context). Isincancellableperiod) {
        abortcurrentthread ();
    }
    else {
        //When cannot abort execution, flush and supress further output
        _endrequiresobservation = true;
    
        if (!_flushing) {//Ignore reponse.end while Flushing (in Onpresendheaders)
            Flush ();
            _ended = true;
    
            if (_context. ApplicationInstance!= null) {
                _context.applicationinstance.completerequest ()}}}}

Watch out! The truth emerges!

Previously thought Response.Redirect would end the current request, the Abortcurrentthread () situation above, if Response.Redirect placed in a try ... The ThreadAbortException exception is caught in the catch.

In general, we redirect,_context in the controller of WebForms page or MVC. The Isincancellableperiod value is true and Abortcurrentthread () is executing, so this problem is not encountered.

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/aspx/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.