HTTP 到 HTTPS 浏览器问题

HTTP to HTTPS Browser issue

几天来我一直在搜索这个问题并做了很多研究,但我就是想不通。

我正在尝试控制我的页面以将它们重定向到 http 或 https,无论我需要与否。

我在 HTTPS

中创建了一个属性,将其放在我需要 运行 的每个页面上方
[AttributeUsage(AttributeTargets.Class)]
public sealed class RequireSSL : Attribute { }

然后我有一个 HttpModule 运行 根据请求检查每个页面。

public class DartsGhentPipeline : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += Context_PreRequestHandlerExecute;
        }

        private void Context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpRequest request = application.Request;
            HttpResponse response = application.Response;
            Page page = application.Context.CurrentHandler as Page;

            if (page == null)
                return;

            bool requireSSL = page.GetType().GetCustomAttributes(typeof(RequireSSL), true).Length > 0;
            bool isSecureConnection = request.IsSecureConnection;
            string url = string.Format("{0}://www.dartsghent.be{1}", requireSSL ? Uri.UriSchemeHttps : Uri.UriSchemeHttp, HttpContext.Current.Request.RawUrl);

            if (requireSSL != isSecureConnection)
                response.RedirectPermanent(url);
        }

        public void Dispose() { }
    }

这里的问题是,当我重定向到相同的 url 或任何其他时。浏览器拒绝从 http 切换到 https 或其他导致重定向循环的方式,浏览器将阻止这种情况发生。

我发现当我将 url 与 www 交替时,我的网站会 运行 完美。或者没有 www。但我不能在我有 test.dartsghent.be

的子网站上使用它

任何人都可以告诉我如何解决这个问题,如果没有 url 重写器模块请问。

感谢任何帮助

注意:我没有使用 MVC

这是 Chrome 输出的示例。

如您所见,页面不断自行重定向。我正在使用 RedirectPermanent(url) 到 https,但即使重定向被触发,它也不会移动到 https,所以它一直在尝试。

假设这是 ASP.NET MVC...

此功能已通过 System.Web.Mvc.RequireHttpsAttribute class.

存在于 MVC v4 中

您正在为 url 变量硬编码 www.blah...

如果您想使用子域,您需要查询原始请求:

string url = requireSSL ? Uri.UriSchemeHttps : Uri.UriSchemeHttp +
             request.Host +
             request.AbsolutePath +
             request.Query;

这超出了我的想象。检查生成的字符串并进行相应调整。

我做了更多研究,发现问题出在我的重定向函数中。 当您重定向到同一个域时,它不会更改协议。所以我所做的是检查域是否为 www。是否在前面,然后重定向到带有 www 的域。前面没有。

如果是子域,这会更难,所以我必须先重定向到另一个页面。否则浏览器将进入循环。

对我来说似乎有点过激,但这是我让它工作的唯一方法。