Wednesday, May 2, 2007

Redirect to SSL

Often times we come across need to redirect (enforcing) a request to SSL. To show how to do that server side, I wrote this blog a while ago and being a popular post, I'm writing a clean code that might help lot of my readers.

First, let's write a utility class that returns whether the request is SSL or not:


/// <summary>
/// Gets if the url is secure or not
/// </summary>
public static bool isSecureURL
{
get
{
// Check the request
if (HttpContext.Current.Request.IsSecureConnection ||
(HttpContext.Current.Request.ServerVariables["HTTPS"] != null &&
HttpContext.Current.Request.ServerVariables["HTTPS"].ToLower() == "on"))
return true;
if ((!string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString())) &&
(HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString().EndsWith("443")))
return true;
// url is not secure:
return false;
}
}


Notice that I use 2 condition checks. The first might work for some users but for others who go through proxy with no forwarding information, I'm trying to see if proxy is forwarding HTTP_HOST ending with SSL port (I use 443).

And now, to implement use something like this:


if (//My Condition to see whether I should implement SSL or not)
{
if (!Utility.isSecureURL)
Response.Redirect(Request.Url.ToString().Replace("http://", "https://"));
}



Love coding!

3 comments:

Anonymous said...

Hi,

I tried this but i hv the following error as,

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Give me the Solution.

blooware said...

You can also try:

Request.IsSecureConnection

Anonymous said...

Or you can check if Request.Url.Scheme contains "https" or not.