Tech Tidbits - Ruby, Ruby On Rails, Merb, .Net, Javascript, jQuery, Ajax, CSS...and other random bits and pieces.

Friday, October 19, 2007

ASP .NET - Redirecting to HTTPS

On a project where I had to install a third party shopping cart, one issue that came up was to make sure all the pages ran under https (many hard coded links used "http").

I put the following code in the Global.asax file:


protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (Request.Url.Port != 443)
{
Response.Redirect ("https://www.yourdomain.com" + Request.Url.AbsolutePath, true);
}
}


This uses


Request.IsSecureConnection


to determine if the call was made over SSL.

So


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



Another way to write this:


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

No comments:

About Me

My photo
Developer (Ruby on Rails, iOS), musician/composer, Buddhist, HSP, Vegan, Aspie.

Labels