Digital Colony!

Detecting HTTP vs HTTPS in ASP.NET

One simple command will let you know if the user is accessing your page via SSL.
Request.IsSecureConnection

Example

if (Request.IsSecureConnection)
{
    Response.Write("HTTPS");
}
else
{
    Response.Write("HTTP");
}

Redirecting to HTTPS

if (!Request.IsSecureConnection)
{
    // send user to SSL 
    string serverName =HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]);        
    string filePath = Request.FilePath;
    Response.Redirect("https://" + serverName + filePath);
}
HttpRequest.IsSecureConnection Property (MSDN)

Labels:

6 Comments:

Blogger Amit said...

That's the best shortcut method that i have found for this.
Thanks a lot!!
I wonder if there are any short commings though!

8/13/2008 11:18 PM

Anonymous Anonymous said...

Wouldn't this catch you in an infinite loop? It seems like it's always going to reference the first request.

9/03/2008 2:50 PM

Blogger MAS said...

It isn't a while loop. The above code shows both the usage and a sample. You would only have a single reference in your code.

It works for me.

9/03/2008 3:05 PM

Blogger RoboChuck said...

Where would you put this in the Code Behind?

Would it be on the Page_Load?

1/12/2009 9:12 AM

Blogger MAS said...

It has been 2 years since I posted this, but I think Page_Load would work.

1/12/2009 9:30 AM

Anonymous Anonymous said...

yes you put it in the code behind. nice code by the way, works like a charm!

1/30/2009 7:51 PM

 

 

Digital Colony Copyright © 1999-2009 XHTML   508
This site uses Blogger, which is not 100% XHTML compliant.
Try...Catch Disclaimer: For brevity many examples do not include error handling. That is your responsibility.