Sunday, December 15, 2013

Redirecting HTTP to HTTPS in mvc

Make sure you have ssl certificate installed and both http and https bindings are set for the website.


In the Global.asax;

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

If you want to make it conditional to the production only, then using the DEBUG switch is an option;

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

Adding or Removing HTTPS Binding

If you are trying to delete a website that is using a wildcard ssl certificate, Or you are trying to remove ssl binding from a website via IIS, you may come across
following type of warning messages.

The certificate associated with this binding is also assigned to another site's binding. Deleting this binding will cause the HTTPS binding of the other site to be unusable. Do you still want to continue?

OR

The certificate associated with this binding is also assigned to another site's binding.  Editing this binding will cause the HTTPS binding of the other site to be unusable. Do you still want to continue?

Solution is to use command prompt to add or remove ssl binding. (Following command was tested on IIS7)

Adding Https Binding

c:\windows\System32\inetsrv>appcmd set site /site.name:"YOURWEBSITE.COM" /+bindings.[protocol='https',bindingInformation='*:443:YOURWEBSITE.COM']

Removing Https Binding

c:\windows\System32\inetsrv>appcmd set site /site.name:"YOURWEBSITE.COM" /-bindings.[protocol='https',bindingInformation='*:443:YOURWEBSITE.COM']


To view all websites/bindings type the following command

appcmd list site