ASP.NET MVC RequireHttps
Asked Answered
R

2

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?

Ramiah answered 15/10, 2009 at 18:59 Comment(0)
F
11

My guess:

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

}
Fishnet answered 15/10, 2009 at 19:2 Comment(4)
That does seem to prevent HTTP requests, but it doesn't redirect to HTTPS.Ramiah
No. This might just be a problem with Visual Studio's ASP.NET Development Server. stackoverflow.com/questions/60113Ramiah
ASP.NET MVC RequireHttps in Production Only: #1640207Ramiah
might be a basic question , as read here and here post request also get encrypted, but like to know weather i should decorate RequireHttps in post also ?Rennold
P
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.

Pipe answered 15/10, 2009 at 22:30 Comment(3)
Be careful when adding this to an action that is intended for the POST method.Illconditioned
@Illconditioned 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.Sassenach
@çağdaş You may want to use this method to change the scheme - should be safer than a string replace: #17968926Laurent
F
11

My guess:

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

}
Fishnet answered 15/10, 2009 at 19:2 Comment(4)
That does seem to prevent HTTP requests, but it doesn't redirect to HTTPS.Ramiah
No. This might just be a problem with Visual Studio's ASP.NET Development Server. stackoverflow.com/questions/60113Ramiah
ASP.NET MVC RequireHttps in Production Only: #1640207Ramiah
might be a basic question , as read here and here post request also get encrypted, but like to know weather i should decorate RequireHttps in post also ?Rennold

© 2022 - 2024 — McMap. All rights reserved.