bx

Switching Between HTTP & HTTPS with .Net

Usually when you build an eCommerce site or a site with a members area you need to set up some secure pages. This means you need to handle the switching between secure and non secure pages. Here is a quick and easy way of doing this.

First thing we need to do is setup some App Settings to our Config file. The two settings we will be adding are:
SSL.Enabled. This is used to bypass the secure page handling if you are running on a local machine where you don’t have any SSL setup.
SSL.Pages. This will contain a comma delimited string of pages that will be secure.

<appSettings>
	<add key="SSL.Enabled" value="true"/>
	<add key="SSL.Pages" value="members.aspx,shop-cart.aspx,billing-shipping.aspx,shop-cart-payment.aspx"/>
</appSettings>

The second thing we need to look at is the actual handling of the secure and non secure pages. I add this functionality to the global.asax under the Application_BeginRequest event. This will check if the page is meant to be secured and if it is it will automatically take them to the secured version.

protected void Application_BeginRequest(object sender, EventArgs e)
{
	string url = Request.Url.ToString();
	string urlLowerCase = url.ToLower();
	if (urlLowerCase.Contains(".aspx"))
	{
		bool sslEnabled;
		bool.TryParse(ConfigurationManager.AppSettings["SSL.Enabled"], out sslEnabled);

		if (sslEnabled)
		{
			var sslPages = ConfigurationManager.AppSettings["SSL.Pages"].ToLower().Split(',');

			foreach (var page in sslPages)
			{
				if (urlLowerCase.Contains(page))
				{
					if (!Request.IsSecureConnection)
					{
						Response.Clear();
						Response.Status = "301 Moved Permanently";
						Response.AddHeader("Location", url.Replace("http://", "https://"));
						Response.End();
					}
					return;
				}
			}

			if (Request.IsSecureConnection)
			{
				Response.Clear();
				Response.Status = "301 Moved Permanently";
				Response.AddHeader("Location", url.Replace("https://", "http://"));
				Response.End();
			}
		}
	}
}

You may have noticed I did not use a Response.Redirect. This is because it would return a 302 Object Moved. A 301 response is better suited to this situation and when dealing search engine spiders.

That’s pretty much it and now you can control your secure pages from your web config file.

⇺ back