Thursday, November 14, 2013

ASP.NET Force HTTPS for all the pages of website

Most of the secured sites have a scenario of permanently redirecting to HTTPS protocol, even if the user tries to access it through HTTP.  

You can easily achieve this by adding a small piece of code in your Application_BeginRequest event in Global.asax file.

  protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            if (ConfigurationManager.AppSettings["HTTPS"] == "1" && HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
            {
                Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl);
            }
        }


The Above code would exclude HTTPS redirection for local environment i.e. localhost too.