Redirecting from http to https with ASP.NET

My first ASP.NET post. Wow – I’m all over the place recently.

Why the post then? Well, I’m learning ASP.NET MVC5. One of the things I need to do is develop a logon page – one of those amazingly complex pieces of code. However, I like to secure my connections, so one of the things I want to do is to Require HTTPS on all pages. How do we do this?

1. Set up your Visual Studio Project for HTTPS Work

Open up the properties for your ASP.NET project – it will look like this:

Screen Shot 2015-01-30 at 3.03.20 PM

Note the SSL Enabled here – set that to True.  Save and Build your project – when you start it up, VS will prompt you to trust the self-signed certificate it created for you – go ahead and do that.  Now you can go to https://localhost:44300/ to get to your project.  Part 1 done.

2. Configure your Controller to Require HTTPS

Open up your AccountController and put at the top of it:

    public class AccountController : Controller

Note the [RequireHttps] attribute – this says that we will only accept HTTPS connections for this entire controller. Repeat this for every single one of your controllers.

When you start your application now, you will note that it fails miserably until you go to https://localhost:44300/Account/Login – then it will let you in.

3. Set up automatic HTTPS Redirection

There are two cases to consider here. When you are developing, your URL is http://localhost:64XXX/ – when you are not developing, your URL is http://something-else/. In both cases, the URL when you are using HTTPS is different. Our redirection needs to take that into account so that we can handle both the development mode and production mode. We do this redirection in the Global.asax.cs file.

        // Redirect http requests to the https URL
        protected void Application_BeginRequest()
            if (!Context.Request.IsSecureConnection)
                // This is an insecure connection, so redirect to the secure version
                UriBuilder uri = new UriBuilder(Context.Request.Url);
                uri.Scheme = "https";
                if (uri.Port > 32000 && uri.Host.Equals("localhost")) {
                    // Development box - set uri.Port to 44300 by default
                    uri.Port = 44300;
                    uri.Port = 443;


The logic in the middle handles the development vs. production switch. When you start your project now, you will first see the HTTP version but it will quickly redirect you to the HTTPS version.