Forcing secure viewing over https in MVC

Suppose you want your application to automatically adjust, to view a page of your application over https even when a user attempts to view the page over http. This can be achieved quite easily with ‘ActionFilterAttribute in mvc.

To do so requires 2 simple steps. Firstly, add the following class to your web project below:

public class SecureAttribute : ActionFilterAttribute


        public bool PermanentRedirect { get; set; }


        public override void OnActionExecuting(ActionExecutingContext filterContext)


            var request = filterContext.HttpContext.Request;


            if (request.IsSecureConnection) return;

            string redirectUrl = request.Url.ToString().Replace(




            filterContext.Result = new RedirectResult(redirectUrl, PermanentRedirect);




Now all that’s left, is to open up your controller class and specify the attribute either preceding the action method, or before the controller class declaration.


[SecureAttribute(PermanentRedirect = true)]

public class AccountController{


       public ActionResult Register(){




And that’s all that is necessary. Now if someone tries to visit, they will be permanently redirected to the same url over https.