SSL pages under ASP.NET MVC

As Amadiere wrote, [RequireHttps] works great in MVC 2 for entering HTTPS. But if you only want to use HTTPS for some pages as you said, MVC 2 doesn't give you any love - once it switches a user to HTTPS they're stuck there until you manually redirect them.

The approach I used is to use another custom attribute, [ExitHttpsIfNotRequired]. When attached to a controller or action this will redirect to HTTP if:

  1. The request was HTTPS
  2. The [RequireHttps] attribute wasn't applied to the action (or controller)
  3. The request was a GET (redirecting a POST would lead to all sorts of trouble).

It's a bit too big to post here, but you can see the code here plus some additional details.


MVCFutures has a 'RequireSSL' attribute.

(thanks Adam for pointing that out in your updated blogpost)

Just apply it to your action method, with 'Redirect=true' if you want an http:// request to automatically become https:// :

    [RequireSsl(Redirect = true)]

See also: ASP.NET MVC RequireHttps in Production Only


If you are using ASP.NET MVC 2 Preview 2 or higher, you can now simply use:

[RequireHttps]
public ActionResult Login()
{
   return View();
}

Though, the order parameter is worth noting, as mentioned here.