Chad
Chad

Reputation: 561

HTTPS Redirect Causing Error "Server cannot append header after HTTP headers have been sent"

I need to check that our visitors are using HTTPS. In BasePage I check if the request is coming via HTTPS. If it's not, I redirect back with HTTPS. However, when someone comes to the site and this function is used, I get the error:

System.Web.HttpException: Server cannot append header after HTTP headers have been sent. at System.Web.HttpResponse.AppendHeader(String name, String value) at System.Web.HttpResponse.AddHeader(String name, String value) at Premier.Payment.Website.Generic.BasePage..ctor()

Here is the code I started with:

// If page not currently SSL
if (HttpContext.Current.Request.ServerVariables["HTTPS"].Equals("off"))
{
    // If SSL is required
    if (GetConfigSetting("SSLRequired").ToUpper().Equals("TRUE"))
    {
        string redi = "https://" +
        HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString() +
        HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"].ToString() +
        "?" + HttpContext.Current.Request.ServerVariables["QUERY_STRING"].ToString();
        HttpContext.Current.Response.Redirect(redi.ToString());
    }
}

I also tried adding this above it (a bit I used in another site for a similar problem):

// Wait until page is copletely loaded before sending anything since we re-build
HttpContext.Current.Response.BufferOutput = true;

I am using c# in .NET 3.5 on IIS 6.

Upvotes: 3

Views: 6130

Answers (2)

Brian Behm
Brian Behm

Reputation: 6299

Chad, Did you try ending the output when you redirect? There is a second parameter that you'd set to true to tell the output to stop when the redirect header is issued. Or, if you are buffering the output then maybe you need to clear the buffer before doing the redirect so the headers are not sent out along with the redirect header.

Brian

Upvotes: 5

AxelEckenberger
AxelEckenberger

Reputation: 16926

This error usually means that something has bee written to the response stream before a redirection is initiated. So you should make sure that the test for https is done fairly high up in the page load function.

Upvotes: 2

Related Questions