How to redirect HTTP to HTTPS in MVC application (IIS7.5)

前端 未结 11 2118
情歌与酒
情歌与酒 2020-11-29 21:39

I need to redirect my HTTP site to HTTPS, have added below rule but I am getting 403 Error when tried using http://www.example.com, it works fine when I type https://www.exa

11条回答
  •  青春惊慌失措
    2020-11-29 22:11

    You can do it in code:

    Global.asax.cs

    protected void Application_BeginRequest(){
        if (!Context.Request.IsSecureConnection)
            Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
    }
    

    Or You could add the same code to an action filter:

    public class SSLFilter : ActionFilterAttribute {
    
        public override void OnActionExecuting(ActionExecutingContext filterContext){
            if (!filterContext.HttpContext.Request.IsSecureConnection){
                var url = filterContext.HttpContext.Request.Url.ToString().Replace("http:", "https:");
                filterContext.Result = new RedirectResult(url);
            }
        }
    }
    

提交回复
热议问题