HTTPS重定向导致错误"服务器无法在发送HTTP标头后追加标头"

Cha*_*had 3 c# https header http

我需要检查我们的访问者是否使用HTTPS.在BasePage中,我检查请求是否来自HTTPS.如果不是,我会使用HTTPS重定向.但是,当有人来到该网站并使用此功能时,我收到错误:

System.Web.HttpException:在发送HTTP标头后,服务器无法附加标头.在Premier.Payment.Website.Generic.BasePage..ctor()的System.Web.HttpResponse.AddHeader(String name,String value)的System.Web.HttpResponse.AppendHeader(String name,String value)处

这是我开始使用的代码:

// 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试在上面添加它(我在另一个站点中使用了一点类似的问题):

// Wait until page is copletely loaded before sending anything since we re-build
HttpContext.Current.Response.BufferOutput = true;
Run Code Online (Sandbox Code Playgroud)

我在IIS 6上使用.NET 3.5中的c#.

Bri*_*ehm 5

Chad,你重定向时尝试结束输出了吗?您可以将第二个参数设置为true,以告知输出在发出重定向标头时停止.或者,如果您正在缓冲输出,那么可能需要在执行重定向之前清除缓冲区,因此标头不会与重定向标头一起发送出去.

布赖恩