SSL pages under ASP.NET MVC

How do I go about using HTTPS for some of the pages in my ASP.NET MVC based site?

Steve Sanderson has a pretty good tutorial on how to do this in a DRY way on Preview 4 at:

http://blog.codeville.net/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/

Is there a better / updated way with Preview 5?,


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.


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


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.