Change the Listening Port on ASP.NET Core 3.1 Kestrel Server and Configure for HTTPS

This article requires ASP.NET Core 3.1 even though it may work with other versions.

The Kestrel server is used by Linux, for example, and it may be necessary to run it with super user privileges depending on the port being used by the Kestrel server. For example, if wanting to run it on ports HTTP/80 or HTTPS/443 then sudo must be used on a Ubuntu installation.

By modifying one line in the Program.cs file, it is possible to change the default port of 5000 that the Kestrel server is listening on.

Here is an example Program.cs file. It now uses the UseUrls() method which takes an array of strings. This array could probably also be saved as a JSON file and then loaded everytime the server is started.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace ProjectName
{
	public class Program
	{
		public static void Main(string[] args)
		{
			CreateHostBuilder(args).Build().Run();
		}

		public static IHostBuilder CreateHostBuilder(string[] args) =>
			Host.CreateDefaultBuilder(args)
				.ConfigureWebHostDefaults(webBuilder =>
				{
					webBuilder.UseStartup<Startup>().UseUrls(new[] { "http://0.0.0.0:5555" }); // NOTE: now the Kestrel server will listen on port 5555!
				});
	}
}

Alternatively, use the command line arguments to specify the ports to listen on.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace ProjectName
{
	public class Program
	{
		public static void Main(string[] args)
		{
			CreateHostBuilder(args).Build().Run();
		}

		public static IHostBuilder CreateHostBuilder(string[] args) =>
			Host.CreateDefaultBuilder(args)
				.ConfigureWebHostDefaults(webBuilder =>
				{
#if DEBUG
					webBuilder.UseStartup<Startup>(); // NOTE: this will be used for DEBUG build so there are no conflicts when running under Visual Studio
#else
					webBuilder.UseStartup<Startup>().UseUrls(args); // NOTE: now the Kestrel server will listen to the URLs specified in the arguments when it is a Release build (Production code)
#endif
				});
	}
}

Issue the commmand dotnet ProjectName.dll http://0.0.0.0:5555 http://0.0.0.0:8080 to make the Kestrel server listen on both ports 5555 and 8080.

Specify http://0.0.0.0:80 and it will listen on port 80 but this requires root priviledges on Linux so run the project executable or DLL with sudo (superuser do).

HTTPS Kestrel Server

See related articles: Compress HTTPS Blazor WASM WebAPI Output and Compress HTTPS .NET Core WebAPI Output

Buy a certificate online or create a self-signed one.

Create Self-signed Certificate

On Windows with the .NET Core SDK installed: dotnet dev-certs https -ep %USERPROFILE%\Desktop\cert.pfx -p your-password

On Linux with the .NET Core SDK installed: dotnet dev-certs https -ep ~/Desktop/cert.pfx -p your-password

Configure the Kestrel Server to Use a Certificate File

In this example, the port can be specified and a password to the certificate file can be specified.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace ProjectName
{
	public class Program
	{
		public static void Main(string[] args) // NOTE: Three arguments should be passed: the port to listen on, the path to the "cert.pfx" file, and the password used for the cert
		{
			CreateHostBuilder(args).Build().Run();
		}

		public static IHostBuilder CreateHostBuilder(string[] args) =>
			Host.CreateDefaultBuilder(args)
				.ConfigureWebHostDefaults(webBuilder =>
				{
					webBuilder.UseStartup<Startup>().UseKestrel(options =>
					{
						int port = 5443; // port defaults to 5443
						if (args.Length > 0)
							int.TryParse(args[0], out port); // args #1 is port
						if (args.Length > 2)
						{
							options.ListenAnyIP(port, listenOptions =>
							{
								listenOptions.UseHttps(args[1], args[2]); // NOTE: args #2 and #3 are path to cert-file.pfx and its password
							});
						}
						else
						{
							options.ListenAnyIP(port);
						}
					});
				});
	}
}

Listen on Both 80 and 443 (SSL) Ports

Here, the default HTTP/HTTPS ports are hard-coded in this example, and the certificate file requires no password. Remember to use super/root user privileges because ports 80 and 443 require root user rights. Apache should not be installed.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace ProjectName
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
            {
#if DEBUG
				webBuilder.UseStartup<Startup>(); // NOTE: this will be used for DEBUG build so there are no conflicts when running under Visual Studio
#else
                if (args.Length == 0)
                {
                    webBuilder.UseStartup<Startup>();
                }
                else
                {
                    webBuilder.UseStartup<Startup>().UseKestrel(options =>
                    {
                        options.ListenAnyIP(443, listenOptions =>
                        {
                            listenOptions.UseHttps(args[0], args.Length > 1 ? args[1] : ""); // args #0 and #1 are path to the certificate.pfx file and its password (if applicable)
                        });
                    }).UseKestrel(options =>
                    {
                        options.ListenAnyIP(80);
                    });
                }
#endif
            });
        }
    }
}

Redirect HTTP/80 requests to HTTPS/443 (SSL)

Here is the Startup.cs file:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ProjectName
{
	public class Startup
	{
		public Startup(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		public IConfiguration Configuration { get; }

		// This method gets called by the runtime. Use this method to add services to the container.
		public void ConfigureServices(IServiceCollection services)
		{
#if !DEBUG
            services.AddHttpsRedirection(options => // NOTE: this will redirect requests to HTTPS/SSL
            {
                options.RedirectStatusCode = (int)System.Net.HttpStatusCode.PermanentRedirect; // NOTE: CAN ALSO USE System.Net.HttpStatusCode.TemporaryRedirect
                options.HttpsPort = 443;
            });
#endif
			services.AddControllersWithViews();
		}

		// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
		public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
		{
#if !DEBUG
            app.UseHttpsRedirection(); // NOTE: USE HTTPS REDIRECTION
#endif
			System.IO.Directory.SetCurrentDirectory(env.ContentRootPath); // NOTE: MAKE SURE TO SET THE CURRENT DIRECTORY TO THE CONTENT ROOT PATH

			if (env.IsDevelopment())
			{
				app.UseDeveloperExceptionPage();
			}
			else
			{
				app.UseExceptionHandler("/Home/Error");
				// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
				app.UseHsts();
			}

			app.UseStaticFiles();

			app.UseRouting();

			app.UseAuthorization();

			app.UseEndpoints(endpoints =>
			{
				endpoints.MapControllerRoute(
					name: "default",
					pattern: "{controller=Home}/{action=Index}/{id?}");
			});
		}
	}
}

Tutorial and Coding Video

https://youtu.be/fUZQdO5yVfI


Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site.
OK