How to force SSL on your ASP.NET website?

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());
    }
}


No Responses

Leave a Reply

Please enter all required information

*

*

*