MVC RequireHttps entire site

前端 未结 9 1040
遇见更好的自我
遇见更好的自我 2020-12-23 13:24

I have read the previous posts about using the RequireHttpsAttribute to secure individual controllers:

ASP.NET MVC RequireHttps in Production Only

but is the

相关标签:
9条回答
  • 2020-12-23 13:37

    Register the RequireHttpsAttribute as a global filter.

    In global.asax:

    protected void Application_Start()
    {
        GlobalFilters.Filters.Add(new RequireHttpsAttribute());
    
        //... other stuff
    }
    
    0 讨论(0)
  • 2020-12-23 13:38

    I ended up using IIS URL Rewrite 2.0 to force the site to switch to HTTPS. This code in web.config does the trick:

      <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>
    
    0 讨论(0)
  • 2020-12-23 13:42

    Just to bring this answer upto date for MVC 3 and above use the following in your Filterconfig.cs file within the App_start folder

            filters.Add(new RequireHttpsAttribute());
    

    Obviously you will need your servers IIS configured to use a valid SSL certificate, cheap certs can be purchased here: https://www.namecheap.com/ i think the last time i purchased one it was $9 per domain per year.

    0 讨论(0)
  • 2020-12-23 13:44

    In Global.asax.cs, use "RegisterGlobalFilters" to register global attributes.

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new RequireHttpsAttribute());
        //e.g. filters.Add(new HandleErrorAttribute());
        //e.g. filters.Add(new System.Web.Mvc.AuthorizeAttribute());            
    }
    
    0 讨论(0)
  • 2020-12-23 13:44

    You could use a base class for all of your controllers, and decorate that with the require ssl attribute.

    0 讨论(0)
  • 2020-12-23 13:46

    In your FilterConfig.cs apply this:

    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
    }
    

    That should force your app to use https on every page.

    0 讨论(0)
提交回复
热议问题