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

Posted by Chad on Stack Overflow See other posts from Stack Overflow or by Chad
Published on 2010-05-26T14:00:54Z Indexed on 2010/05/26 14:31 UTC
Read the original article Hit count: 728

Filed under:
|
|
|

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.

enter code here

© Stack Overflow or respective owner

Related posts about c#

Related posts about http