Wednesday, May 2, 2007

Redirect to SSL: When Request.ServerVariables["HTTPS"] doesn’t work…

How we go about enforcing a page, say a purchase page, to be on SSL? Sure we can enforce in IIS; but we all want to redirect to https version if some how the request comes with http instead (and don’t want to give an error page). One way some of us do is by checking the HTTPS Server Variable (and some doing some other methods).

However, if we are in a situation like the on I happened to be recently, where the proxy’s pretty much don’t tell anything including https server variable (always comes as “off”) we would be puzzled how to handle it. Well, if we closely look at all the server variables we might find some other clues to know about it and in our case it happened to be the suffix of the HTTP_HOST server variable. We looked at server variables with a code like:

foreach (string eachKey in Request.ServerVariables.Keys)

Response.Write(String.Format("{0} = {1}<br>",

eachKey, Request.ServerVariables[eachKey].ToString()));

May be not the best method, but we got a work around for our purpose with a code that looks like:

Code that didn’t work:

if (ConfigurationManager.AppSettings["SecureServer"].ToString().ToLower() == "true" &&

Request.ServerVariables["HTTPS"].ToLower() == "off")

Response.Redirect(Request.Url.ToString().Replace("http://", "https://"), true);

Code that worked:

if (ConfigurationManager.AppSettings["SecureServer"].ToString().ToLower() == "true" &&

(!string.IsNullOrEmpty(Request.ServerVariables["HTTP_HOST"].ToString())) &&

(!Request.ServerVariables["HTTP_HOST"].ToString().EndsWith("443")))

Response.Redirect(Request.Url.ToString().Replace("http://", "https://"), true);

Love coding!

0 comments: