Force SSL on a C# Website

Here is a simple way to force SSL on a C# website

Posted on May 31, 2016 7:54AM

Here is a simple solution I use to force an application to use SSL. Normally, I have added the debug statement to prevent this from firing if you are debugging the site. This goes in the Global.asax file.

Force SSL

        protected void Application_BeginRequest(Object source, EventArgs e)
        {
            if (!Context.Request.IsSecureConnection)
            {
#if !DEBUG
                Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"));
#endif
            }
        }

Force SSL Except for specific URL

        protected void Application_BeginRequest(Object source, EventArgs e)
        {
            if (!Context.Request.IsSecureConnection)
            {
#if !DEBUG
                string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
                    Request.ApplicationPath.TrimEnd('/') + "/";
                if (baseUrl != "http://yourtestsite.com/")
                    Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"));
#endif
            }
        }