简体   繁体   中英

ASP.NET 3.5, googlebot, 301 Redirect “Cannot redirect after HTTP headers have been sent”

I have set up a dynamic 301 redirect routine within a custom HttpModule. The code accepts the incoming url, parses the querystring, and using a config and app specific logic, redirects to a new SEO friendly url using the following code:

if (HttpContext.Current.Response.IsRequestBeingRedirected)
    return;

if (!HttpContext.Current.Response.IsClientConnected)
{
    response.End();
    return;
}

response.Redirect(newLocation, false);
response.Status = "301 Moved Permanently";
response.StatusCode = 301;

This works fine and dandy if you enter a legacy url directly in a web browser. However, my event log is showing a bunch of "Cannot redirect after HTTP headers have been sent" HttpExceptions when the same url is accessed by the googlebot (66.249.71.11).

I'm at a loss as to what the issue is and how to resolve it.

In ASP.NET 3.5 Response.Redirect automatically sends a 302 (rather than a 301) and terminates the connection with the client. If you want to use a 301 then you have to manually insert all of the headers. Something like the following:

Response.Clear();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","/about.aspx");
Response.End();

Alternatively you can upgrade to ASP.NET 4.0 where there is now a method to indicate something has moved permanently.

Response.RedirectPermanent("/about.aspx");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM