views:

809

answers:

2

How do I use the ASP.NET MVC 2 Preview 2 Futures RequireHttps attribute?

I want to prevent unsecured HTTP requests from being sent to an action method. I want to automatically redirect to HTTPS.

MSDN:

How do I use this feature?

+1  A: 

My guess:

[RequireHttps] //apply to all actions in controller
public class SomeController 
{
  //... or ...
  [RequireHttps] //apply to this action only
  public ActionResult SomeAction()
  {
  }

}
Jan Willem B
That does seem to prevent HTTP requests, but it doesn't redirect to HTTPS.
Zack Peterson
No. This might just be a problem with Visual Studio's ASP.NET Development Server. http://stackoverflow.com/questions/60113/
Zack Peterson
ASP.NET MVC RequireHttps in Production Only: http://stackoverflow.com/questions/1639707/asp-net-mvc-requirehttps-in-production-only
Zack Peterson
+4  A: 

I think you're going to need to roll your own ActionFilterAttribute for that.

public class RedirectHttps : ActionFilterAttribute {
   public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (!filterContext.HttpContext.Request.IsSecureConnection) {
            filterContext.Result = 
                new RedirectResult(filterContext.HttpContext.Request.Url.
                    ToString().Replace("http:", "https:"));
            filterContext.Result.ExecuteResult(filterContext);
        }
        base.OnActionExecuting(filterContext);
    }
}

Then in your controller :

public class HomeController : Controller {

    [RedirectHttps]
    public ActionResult SecuredAction() {
        return View();
    }
}

You might want to read this as well.

çağdaş
Be careful when adding this to an action that is intended for the POST method.
Carl