MVC RequireHttps整个网站

Cod*_*rue 62 asp.net-mvc ssl

我已经阅读了之前关于使用RequireHttpsAttribute保护单个控制器的帖子:

ASP.NET MVC RequireHttps仅适用于生产

但有没有办法将其应用到整个网站?由于我的主机(discountasp.net)我不能使用"RequireSSL IIS"设置.

hwi*_*ers 121

注册RequireHttpsAttribute为全局过滤器.

在global.asax中:

protected void Application_Start()
{
    GlobalFilters.Filters.Add(new RequireHttpsAttribute());

    //... other stuff
}
Run Code Online (Sandbox Code Playgroud)

  • @RacielR.我之前遇到过同样的问题,问题是托管合作伙伴在防火墙上接受了ssl,但是通过http将请求发送到我的服务器......请确保您的托管合作伙伴不做同样的事情. (4认同)
  • 这是一个干净的解决方案,但它不适用于MVC控制器吗?如果您想为_any_ URL强制执行HTTPS,包括静态资源或旧版Web窗体aspx页面,该怎么办?似乎URL Rewrite方法是最普遍的.甚至可以用于iisnode中托管的Node.js应用程序(我知道因为我正在这样做). (2认同)
  • RequireHttpsAttribute发送302(临时redir)而不是301(永久),这可能会伤害SEO.http://benjii.me/2015/10/redirect-to-https-asp-net-mvc/ (2认同)

Cod*_*rue 22

我最终使用IIS URL Rewrite 2.0强制网站切换到HTTPS.web.config中的这段代码可以解决这个问题:

  <system.webServer>
    <!-- This uses URL Rewrite 2.0 to force the entire site into SSL mode -->
    <rewrite xdt:Transform="Insert">
      <rules>
        <rule name="Force HTTPS" enabled="true">
          <match url="(.*)" ignoreCase="false" />
          <conditions>
            <add input="{HTTPS}" pattern="off" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
Run Code Online (Sandbox Code Playgroud)

  • 对于像我这样多年后发现这一点的人来说,这在 vs2017 中给我带来了错误。以下与此类似的答案有效:/sf/answers/3296681/ (2认同)

Tod*_*ith 19

您始终可以在global.asax中的应用程序级别添加检查

protected void Application_BeginRequest(Object sender, EventArgs e)
{
   if (!HttpContext.Current.Request.IsSecureConnection)
   {
    Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
                                 + HttpContext.Current.Request.RawUrl);
   }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*ens 14

只是为了使MVC 3及更高版本的答案更新,请在App_start文件夹中的Filterconfig.cs文件中使用以下内容

        filters.Add(new RequireHttpsAttribute());
Run Code Online (Sandbox Code Playgroud)

显然你需要你的服务器IIS配置为使用有效的SSL证书,可以在这里购买廉价证书:https://www.namecheap.com/我认为我最后一次购买一个,每个域每年9美元.


joe*_*tea 12

在您的FilterConfig.cs中应用此:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
     // only if Debug is not enabled, do not require https for local development
     if (!HttpContext.Current.IsDebuggingEnabled)
          filters.Add(new RequireHttpsAttribute());

     //... any other filters
}
Run Code Online (Sandbox Code Playgroud)

这应该会强制您的应用在每个页面上使用https.