在 MVC5 应用程序上强制使用 HTTPS 时出现 ERR_TOO_MANY_REDIRECTS

Woj*_*jna 1 c# asp.net iis ssl https

我将 OVH Server 与 SSL Gateway Free 一起使用,我在其中托管了我的 MVC5 应用程序。

当我试图仅强制 HTTPS 连接时,我的浏览器显示:

“ERR_TOO_MANY_REDIRECTS”。

我正在尝试各种事情和解决方案,但没有一个奏效。

我在我的项目属性中启用了 SSL,尝试通过我的 IIS 上的 URL 重写重定向,然后是本教程和许多其他教程[RequireHttps]在我的BaseController以及Application_BeginRequest()Global.asax 中的许多配置中使用。

铁:

protected void Application_BeginRequest()
{
    if (!Context.Request.IsSecureConnection)
    {
        // This is an insecure connection, so redirect to the secure version
        UriBuilder uri = new UriBuilder(Context.Request.Url);
        if (!uri.Host.Equals("localhost"))
        {
            uri.Port = 443;
            uri.Scheme = "https";
            Response.Redirect(uri.ToString());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不知道如何强制只使用 HTTPS 连接。

Woj*_*jna 5

@PeteG 回答是对的。IsSecureConnection 无法正常工作,您所要做的就是使用以下代码:

      protected void Application_BeginRequest()
    {
        var loadbalancerReceivedSslRequest = string.Equals(Request.Headers["X-Forwarded-Proto"], "https");
        var serverReceivedSslRequest = Request.IsSecureConnection;

        if (loadbalancerReceivedSslRequest || serverReceivedSslRequest) return;

        UriBuilder uri = new UriBuilder(Context.Request.Url);
        if (!uri.Host.Equals("localhost"))
        {
            uri.Port = 443;
            uri.Scheme = "https";
            Response.Redirect(uri.ToString());
        }
    }
Run Code Online (Sandbox Code Playgroud)