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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Be careful when adding this to an action that is intended for the POST method.
@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.
@çağdaş You may want to use this method to change the scheme - should be safer than a string replace: stackoverflow.com/questions/17968426/…
11

My guess:

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

}

4 Comments

That does seem to prevent HTTP requests, but it doesn't redirect to HTTPS.
No. This might just be a problem with Visual Studio's ASP.NET Development Server. stackoverflow.com/questions/60113
ASP.NET MVC RequireHttps in Production Only: stackoverflow.com/questions/1639707/…
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 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.