Redirect Http to Https C#.

Umbraco 7 and C#

This blog is in 3 parts and is based on a fictitious company that sells goods and allows visitors to add comments.

  1. The company needs all pages to be over HTTPS, so we need some way of achieving this.
  2. The items sold by the company need to have microdata tags to help visitors see the items for sale on search engines.
  3. Visitors can leave a comment, but before the comment can is shown, it needs to be viewed by a member of staff.

First, we need to create a new solution in Visual Studio with two projects called Web.UI and Web.Model and then add Umbraco and Archetype to both projects.

This example uses Umbraco version 7.5.10 and Archetype 1.13.2.

After all the NuGet packages have been installed, rebuilt the project and run, as this is a new project you will see Umbraco's default page where you need to add your username and password.

Once you have entered your details, create a home page and items for sale page.

We now need to create the module that will force all pages to display with HTTPS, using the code below.

Module Code.

using System;
using System.Web;
namespace Web.Model.HttpsModule
{
    /// 
    /// Redirects all pages to https.
    /// 
    public class RedirectToHttps : IHttpModule
    {
        public void Init(HttpApplication app)
        {
            app.BeginRequest += (app_BeginRequest);
        }
        private void app_BeginRequest(object sender, EventArgs e)
        {
            int securePort = 443;
            if (!HttpContext.Current.Request.IsSecureConnection || HttpContext.Current.Request.Url.Port != securePort)
            {
                string redirectUrl = HttpContext.Current.Request.Url.ToString().Replace("http:", "https:");
                HttpContext.Current.Response.RedirectPermanent(redirectUrl);
            }
        }
        public void Dispose()
        {
            // Needed for IHttpModule
        }
    }
}

If everything works OK, you can now run a page under HTTP and the module will force the page to display under HTTPS.