Change default Kestrel port in ASP.NET Core

February 10, 2017
.NET Core

You configure Kestrel to run from a different port than 5000.

UseUrls extension

var host = new WebHostBuilder()
	.UseKestrel()
	.UseContentRoot(Directory.GetCurrentDirectory())
	.UseUrls($"http://localhost:5001")
	.UseIISIntegration()
	.UseStartup()
	.Build();

appsettings.json

Add urls in appsettings.json "urls": "http://localhost:50001"

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: true)
    .Build();

var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
	.UseConfiguration(config)
    .UseIISIntegration()
    .UseStartup()
    .Build();

I prefer to get the port as a command line argument.

.UseUrls($"http://localhost:{GetPort(args)}")

private static int GetPort(string[] args)
{
    for (var i = 0; i < args.Length; i++)
    {
        if (args[i].ToLower() == "--port")
        {
            int port;
            if (i + 1 < args.Length && int.TryParse(args[i + 1], out port))
                return port;
        }
    }

    return 5000;
}

The port can now be supplied as an argument --port 5001

dotnet run --port 5001
# Or
/usr/bin/dotnet path-to-dll --port 5001