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

有没有更好的方法,比如web。config中的一些设置?


当前回答

在IIS10 (Windows 10和Server 2016)中,从1709版本开始,有一个新的、更简单的选项可以为网站启用HSTS。

微软在这里描述了新方法的优点,并提供了许多不同的示例,说明如何通过编程或直接编辑ApplicationHost实现更改。配置文件(类似web。配置,但操作在IIS级别,而不是个别站点级别)。ApplicationHost。config可以在c:\ windows \ system32 \inetsrv\config目录下找到。

我在这里概述了避免链接失效的两个示例方法。

方法1 -编辑ApplicationHost。配置文件 在<site>标签之间,添加这一行:

<hsts enabled="true" max-age="31536000" includeSubDomains="true" redirectHttpToHttps="true" />

方法2—命令行: 从升高的命令提示符(即在CMD上用鼠标右键并以管理员身份运行)执行以下命令。请记住在IIS管理器中显示的站点名称与Contoso交换。

c:
cd C:\WINDOWS\system32\inetsrv\
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.enabled:True" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.max-age:31536000" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.includeSubDomains:True" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.redirectHttpToHttps:True" /commit:apphost

如果您处于访问受限的托管环境中,那么微软在文章中提供的其他方法可能是更好的选择。

请记住,IIS10版本1709现在可以在Windows 10上使用,但对于Windows Server 2016,它在不同的发布轨道上,并且不会作为补丁或服务包发布。点击这里了解1709年的详细信息。

其他回答

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

从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日取代)

基本上

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)

我不知道如何在web.config中指定它

I'm going to throw my two cents in. IF you have access to IIS server side, then you can force HTTPS by use of the protocol bindings. For example, you have a website called Blah. In IIS you'd setup two sites: Blah, and Blah (Redirect). For Blah only configure the HTTPS binding (and FTP if you need to, make sure to force it over a secure connection as well). For Blah (Redirect) only configure the HTTP binding. Lastly, in the HTTP Redirect section for Blah (Redirect) make sure to set a 301 redirect to https://blah.com, with exact destination enabled. Make sure that each site in IIS is pointing to it's own root folder otherwise the Web.config will get all screwed up. Also make sure to have HSTS configured on your HTTPSed site so that subsequent requests by the browser are always forced to HTTPS and no redirects occur.

在IIS10 (Windows 10和Server 2016)中,从1709版本开始,有一个新的、更简单的选项可以为网站启用HSTS。

微软在这里描述了新方法的优点,并提供了许多不同的示例,说明如何通过编程或直接编辑ApplicationHost实现更改。配置文件(类似web。配置,但操作在IIS级别,而不是个别站点级别)。ApplicationHost。config可以在c:\ windows \ system32 \inetsrv\config目录下找到。

我在这里概述了避免链接失效的两个示例方法。

方法1 -编辑ApplicationHost。配置文件 在<site>标签之间,添加这一行:

<hsts enabled="true" max-age="31536000" includeSubDomains="true" redirectHttpToHttps="true" />

方法2—命令行: 从升高的命令提示符(即在CMD上用鼠标右键并以管理员身份运行)执行以下命令。请记住在IIS管理器中显示的站点名称与Contoso交换。

c:
cd C:\WINDOWS\system32\inetsrv\
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.enabled:True" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.max-age:31536000" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.includeSubDomains:True" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.redirectHttpToHttps:True" /commit:apphost

如果您处于访问受限的托管环境中,那么微软在文章中提供的其他方法可能是更好的选择。

请记住,IIS10版本1709现在可以在Windows 10上使用,但对于Windows Server 2016,它在不同的发布轨道上,并且不会作为补丁或服务包发布。点击这里了解1709年的详细信息。

你需要做的是:

1)在web中添加一个键。配置,取决于生产或阶段服务器如下所示

<add key="HttpsServer" value="stage"/>
             or
<add key="HttpsServer" value="prod"/>

2)在Global内部。Asax文件添加如下方法。

void Application_BeginRequest(Object sender, EventArgs e)
{
    //if (ConfigurationManager.AppSettings["HttpsServer"].ToString() == "prod")
    if (ConfigurationManager.AppSettings["HttpsServer"].ToString() == "stage")
    {
        if (!HttpContext.Current.Request.IsSecureConnection)
        {
            if (!Request.Url.GetLeftPart(UriPartial.Authority).Contains("www"))
            {
                HttpContext.Current.Response.Redirect(
                    Request.Url.GetLeftPart(UriPartial.Authority).Replace("http://", "https://www."), true);
            }
            else
            {
                HttpContext.Current.Response.Redirect(
                    Request.Url.GetLeftPart(UriPartial.Authority).Replace("http://", "https://"), true);
            }
        }
    }
}

这是基于@特洛伊·亨特的更全面的回答。将这个函数添加到Global.asax.cs中的WebApplication类中:

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        // Allow https pages in debugging
        if (Request.IsLocal)
        {
            if (Request.Url.Scheme == "http")
            {
                int localSslPort = 44362; // Your local IIS port for HTTPS

                var path = "https://" + Request.Url.Host + ":" + localSslPort + Request.Url.PathAndQuery;

                Response.Status = "301 Moved Permanently";
                Response.AddHeader("Location", path);
            }
        }
        else
        {
            switch (Request.Url.Scheme)
            {
                case "https":
                    Response.AddHeader("Strict-Transport-Security", "max-age=31536000");
                    break;
                case "http":
                    var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
                    Response.Status = "301 Moved Permanently";
                    Response.AddHeader("Location", path);
                    break;
            }
        }
    }

(要在本地构建中启用SSL,请在项目的Properties dock中启用它)