views:

200

answers:

2

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
A: 

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.

Obalix
It is currently the first thing done in the BasePage constructor, so it should be about the first thing done overall.
Chad
A: 

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

Brian Behm
Thanks Brian! You da man. I added the second parameter "true" to end the response, and added "return;" in the next line to be sure the page stopped running. HttpContext.Current.Response.Redirect(redi.ToString(), true); return;
Chad