Monday, August 20, 2007

How to force a page to use SSL (HTTPS)

The following sample code will force pages to use SSL (https) with ASP.NET 2.0:

//this is the current url 
System.Uri currentUrl = System.Web.HttpContext.Current.Request.Url;
//don't redirect if this is localhost
if (!currentUrl.IsLoopback)
    if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
        //build the secure uri
        System.UriBuilder secureUrlBuilder = new UriBuilder(currentUrl);
        secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
        //use the default port. 
        secureUrlBuilder.Port = -1;
        //redirect and end the response.

Hope it helps.


Vaibhav Kamath said...

This is an awesome code. I was searching for "how to force SSL with ASP.NET" and found links that required changes to IIS. This code is simple and elegant.

Thank you for sharing,

Patty said...

You write very well.