12

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?

Zack Peterson
  • 56,055
  • 78
  • 209
  • 280

2 Answers2

16

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ş Tekin
  • 16,592
  • 4
  • 49
  • 58
  • Be careful when adding this to an action that is intended for the POST method. – Carl Apr 27 '10 at 13:43
  • 1
    @Carl why? because the post data is lost? If you want to ensure that sensitive data not being posted over non https, then you shouldn't process that data. – eglasius Jun 16 '11 at 03:23
  • 1
    @çağdaş You may want to use this method to change the scheme - should be safer than a string replace: http://stackoverflow.com/questions/17968426/changing-the-scheme-of-system-uri – Evan M Feb 18 '14 at 15:24
11

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
  • 3,787
  • 1
  • 25
  • 39
  • 1
    That does seem to prevent HTTP requests, but it doesn't redirect to HTTPS. – Zack Peterson Oct 15 '09 at 19:09
  • No. This might just be a problem with Visual Studio's ASP.NET Development Server. http://stackoverflow.com/questions/60113/ – Zack Peterson Oct 15 '09 at 19:10
  • 5
    ASP.NET MVC RequireHttps in Production Only: http://stackoverflow.com/questions/1639707/asp-net-mvc-requirehttps-in-production-only – Zack Peterson Nov 10 '09 at 21:55
  • might be a basic question , as read [here](http://security.stackexchange.com/questions/12531/ssl-with-get-and-post) and [here](http://stackoverflow.com/questions/499591/are-https-urls-encrypted) `post` request also get encrypted, but like to know weather i should decorate `RequireHttps` in post also ? – Shaiju T Feb 22 '16 at 16:26