How to redirect HTTP to HTTPS in MVC application

How to redirect HTTP to HTTPS in MVC application

In <system.webServer>

Following ASP.NET MVC rewrite rule in Web.config file

<system.webServer>
    <rewrite>
      <outboundRules>
        <rule name="Append 'Vary: Accept-Encoding' header" patternSyntax="ECMAScript">
          <match serverVariable="RESPONSE_VARY" pattern=".+" />
          <action type="Rewrite" value="{R:0}, Accept-Encoding" replace="true" />
        </rule>
        <rule name="Set 'Vary: Accept-Encoding' header if no others" patternSyntax="ECMAScript">
          <match serverVariable="RESPONSE_VARY" pattern=".+" negate="true" />
          <action type="Rewrite" value="Accept-Encoding" />
        </rule>
      </outboundRules>
    </rewrite>
  </system.webServer>

In Global.asax

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:"));
    }
}

2020-03-19