Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC RequireHttps

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:

  • RequireHttpsAttribute
  • RequireHttpsAttribute Members
  • RequireHttpsAttribute.HandleNonHttpsRequest Method

How do I use this feature?

like image 640
Zack Peterson Avatar asked Oct 15 '09 18:10

Zack Peterson


People also ask

What is RequireHttps?

The RequireHttps Attribute in ASP.NET MVC forces an unsecured HTTP request to be re-sent over HTTPS.

What is ValidateInput MVC?

The ValidateInput attribute is used to allow sending the HTML content or codes to the server which, by default, is disabled by ASP.NET MVC to avoid XSS (Cross-Site Scripting) attacks. This attribute is used to enable or disable the request validation. By default, request validation is enabled in ASP.NET MVC.


2 Answers

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.

like image 189
Çağdaş Tekin Avatar answered Sep 28 '22 09:09

Çağdaş Tekin


My guess:

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

}
like image 44
Jan Willem B Avatar answered Sep 28 '22 10:09

Jan Willem B