0

We have simple code below:

string returnUrl = "/sitecore/content/;
WebUtil.Redirect(returnUrl);

However, the the last line above seems to throw an exception below:

6156 2016:11:18 06:41:01 ERROR Application error.
Exception: System.Web.HttpException
Message: Cannot redirect after HTTP headers have been sent.
Source: System.Web
   at System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent)
   at Sitecore.Web.WebUtil.Redirect(String path)

Any idea what could be throwing this excpetion?

  • 1
    Does this help explain? stackoverflow.com/a/159538/1277533 – Michael West Nov 21 '16 at 5:25
  • It looks like you are trying to redirect inside rendering, but it is too late - you sitecore already began to render html and sent headers. – Daniil Nov 21 '16 at 15:23
2

This exception can happen in at least 2 cases:

  1. There is already a redirect that has been initiated earlier during the page request.

  2. Your application wrote other headers to the response before WebUtil.Redirect was called.

In both cases, you should get a clue about what's happening by setting a breakpoint on the line with WebUtil.Redirect and looking at the values stored in Response.Headers.

If there's already a redirect header, the best thing to do is make sure your redirection logic is consolidated in one place—then there won't be room for such errors.

If you can't control previous redirects, then you can guard against them:

if (!Response.IsRequestBeingRedirected)
{
    string returnUrl = "/sitecore/content/";
    WebUtil.Redirect(returnUrl);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.