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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading How to force SSL on your ASP.NET website? at vaibhavkamath.info.

meta

%d bloggers like this: