asp.net 中为整个站点强制使用 https 的最佳方法? [英] Best way in asp.net to force https for an entire site?

查看:27
本文介绍了asp.net 中为整个站点强制使用 https 的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大约 6 个月前,我推出了一个网站,其中每个请求都需要通过 https.当时我能找到的确保每个页面请求都通过 https 的唯一方法是在页面加载事件中检查它.如果请求不是通过 http 我会 response.redirect("https://example.com")

About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("https://example.com")

有没有更好的方法——最好在 web.config 中进行一些设置?

Is there a better way -- ideally some setting in the web.config?

推荐答案

请使用 HSTS (HTTP 严格传输安全)

Please use HSTS (HTTP Strict Transport Security)

来自 http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
                        redirectType="Permanent" />
                </rule>
            </rules>
            <outboundRules>
                <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
                    <match serverVariable="RESPONSE_Strict_Transport_Security"
                        pattern=".*" />
                    <conditions>
                        <add input="{HTTPS}" pattern="on" ignoreCase="true" />
                    </conditions>
                    <action type="Rewrite" value="max-age=31536000" />
                </rule>
            </outboundRules>
        </rewrite>
    </system.webServer>
</configuration>

原始答案(于 2015 年 12 月 4 日替换为上述内容)

Original Answer (replaced with the above on 4 December 2015)

基本上

protected void Application_BeginRequest(Object sender, EventArgs e)
{
   if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
   {
    Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+   HttpContext.Current.Request.RawUrl);
   }
}

这将进入 global.asax.cs(或 global.asax.vb)

that would go in the global.asax.cs (or global.asax.vb)

我不知道在 web.config 中指定它的方法

i dont know of a way to specify it in the web.config

这篇关于asp.net 中为整个站点强制使用 https 的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆