I have read the previous posts about using the RequireHttpsAttribute to secure individual controllers:
ASP.NET MVC RequireHttps in Production Only
but is the
Register the RequireHttpsAttribute
as a global filter.
In global.asax:
protected void Application_Start()
{
GlobalFilters.Filters.Add(new RequireHttpsAttribute());
//... other stuff
}
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>
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.
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());
}
You could use a base class for all of your controllers, and decorate that with the require ssl attribute.
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.