How to force SSL on your ASP.NET website?

March 27, 2008 § Leave a comment

I have seen may implementations of forcing SSL on websites that require changes to IIS and creating dummy aspx pages for the redirect, but nothing beats the simple and elegant code that follows:

Courtesy: IKOSoftware

// Force SSL
//
Uri currentUrl = System.Web.HttpContext.Request.Url;
if (!currentUrl.IsLoopback)
{
    if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, 
                                  StringComparison.CurrentCultureIgnoreCase))
    {
        // Build the Secure Uri
        //
        UriBuilder secureUrlBuilder = new UriBuilder(currentUrl);
        secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
    
        // Use the default port.
        //
        secureUrlBuilder.Port = -1;
    
        // Redirect and end the response
        //
        System.Web.HttpContext.Response.Redirect(secureUrlBuilder.Uri.ToString());
    }
}

Where Am I?

You are currently viewing the archives for March, 2008 at vaibhavkamath.info.