HTTPS Redirect Causing Error "Server cannot add header after sending HTTP headers"

I need to check that our visitors use HTTPS. In BasePage, I check to see if the request comes in via HTTPS. If it is not, I am redirecting back using HTTPS. However, when someone comes to the site and this function is used, I get an error message:

System.Web.HttpException: The server cannot add the header after the HTTP headers are sent. in System.Web.HttpResponse.AppendHeader (String name, String value) in System.Web.HttpResponse.AddHeader (String name, String value) in 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 (a bit I used on 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.

+3
2

, ? , true, , . , , , , .

+5

, - . , https .

+2

Source: https://habr.com/ru/post/1747203/


All Articles