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

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

推荐答案

请使用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>

Original Answer(于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中指定它

Asp.net相关问答推荐

ASP.NET Core 延迟加载始终返回 null

你能从请求变量中确定时区吗?

判断 asp.net mvc 4 应用程序中的 ssl 协议、密码和其他属性

httpCompression 和 urlCompression 有什么区别?

HttpResponse 的区别:SetCookie、AppendCookie、Cookies.Add

说服遗留应用程序 VB6 开发人员切换到 C#

是否可以访问位于另一个项目中的 MVC 视图?

WebAPI 请求流支持

System.Web.Helpers.Crypto - 盐在哪里?

如何在 ASP.NET core rc2 中禁用浏览器缓存?

将 ListItem 的 ASP.NET 列表数据绑定到 DropDownList 问题

为什么对 ASP.NET MVC 控制器的调用不执行 DelegatingHandler?

将数据表导出到 Excel 文件

如何获取正在访问 ASP.NET 应用程序的当前用户?

如何获取程序集的最后修改日期?

覆盖静态方法

ASP.Net 无法创建/卷影复制

验证请求事件

如何使用 jquery 设置单选按钮 Select 的值

重新生成designer.cs