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

前端 未结 11 2108
情歌与酒
情歌与酒 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:00

    To force https only when the website is lunched on the server and ignore it while running the website on your machine for development :

    In Global.asax :

    You'll need the Application_BeginRequest() method

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
             // .....
        }
    
        //force https on server, ignore it on local machine
        protected void Application_BeginRequest()
        {
            if (!Context.Request.IsSecureConnection && !Context.Request.Url.ToString().Contains("localhost"))
                Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
        }
    }
    

提交回复
热议问题