Force SSL ON or OFF Function

When working on a site that may have some pages in SSL (the check out pages) and most pages not I use a function to switch between SSL and Non SSL pages.

First, I set the non secure and SSL URL’s in the config file under appSettings:

    <add key=”SSLURL” value=”https://www.mydomain.com”/>
    <add key=”NonSSLURL” value=”http://www.mydomain.com”/>

Next, in my utility class I add this function:

    Public Function PageStartUp()
        If Request.ServerVariables(“HTTPS”).ToLower = “on” And Not gIsSSLRequired Then
            If Request.QueryString.ToString.Length > 0 Then
                Response.Redirect(ConfigurationManager.AppSettings(“NonSSLURL”) & Request.ServerVariables(“SCRIPT_NAME”) & “?” & Request.QueryString.ToString)
            Else
                Response.Redirect(ConfigurationManager.AppSettings(“NonSSLURL”) & Request.ServerVariables(“SCRIPT_NAME”))
            End If
        End If
        If Request.ServerVariables(“HTTPS”).ToLower = “off” And gIsSSLRequired And ConfigurationManager.AppSettings(“SSLURL”).ToLower.Substring(0,5)=”https” Then
            If Request.QueryString.ToString.Length > 0 Then
                Response.Redirect(ConfigurationManager.AppSettings(“SSLURL”) & Request.ServerVariables(“SCRIPT_NAME”) & “?” & Request.QueryString.ToString)
            Else
                Response.Redirect(ConfigurationManager.AppSettings(“SSLURL”) & Request.ServerVariables(“SCRIPT_NAME”))
            End If
        End If
        Return True
    End Function

Be sure to add the public variable gIsSSLRequired in the class as well.

Then in the page load event of each page I add the following:

gIsSSLRequired = True
Call PageStartUp()

Cool, huh?