Securing your ASP.NET Core site with HTTPS

Migrating to HTTPS

Google ranks HTTPS sites higher and with a few changes, you can migrate your ASP.NET Core site to HTTPS. After you purchase and install an SSL certificate from your hosting provider, you will need to modify your startup.cs to use this certificate. You will also want to secure your local site for testing.

Using Visual Studio, you can secure your local site by selecting your project Properties from the Project menu item. In this configuration page, check the “Enable SSL” checkbox. This will show you the port where your local website will load as HTTPS.

Modify your startup.cs file

Open the starup.cs file. Under the ConfigureServices method, add the option to require HTTPS as follows.


 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(new RequireHttpsAttribute());
            })
...... more code
        }

In the Configure method, add the code to redirect to your HTTPS port.


 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
          if (env.IsDevelopment())
            {
               .... more code
                var options = new RewriteOptions()
             .AddRedirectToHttps(StatusCodes.Status301MovedPermanently, 44348);
                app.UseRewriter(options);

            }
            else
            {
                .... more code
                var options = new RewriteOptions()
             .AddRedirectToHttps(StatusCodes.Status301MovedPermanently, 443);
                app.UseRewriter(options);

            }
            .......... more code
      }

So that you can test locally, it is important to redirect to the local HTPPS port for the local environment. For your production environment, the default HTTPS port is 443, but you might need to verify this with your hosting provider.

Test this locally, then publish to your provider. You will now have a secure site.

Leave a Reply

Your email address will not be published. Required fields are marked *