Full source code available CoreWithKestrelFromConfighere.
In my previous post I explained how to host Kestrel web server running on (the default) port 5000 as a Windows service. But what if you want to run the server on a different port?
There are a few ways to do this, but the easiest is to add an entry to the appsettings.json
file specifying the urls the server should listen to.
In this example, I’m setting it to http://localhost:62000.
The appsettings.json file looks like this –
{
"urls": "http://localhost:62000/"
}
I also removed applicationUrl
setting from the from the launchSettings.json
file, now Visual Studio and the command line will set the application to the same port.
To add the settings in appsettings.json
to the configuration, call .AddJsonFile("appsettings.json")
when creating the ConfigurationBuilder
.
public class Program { public static IConfiguration Configuration { get; set; } public static void Main(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); Configuration = builder.Build(); BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseConfiguration(Configuration) .Build(); }
You don’t have name the file appsettings.json, you can put it any file you like, but this is convenient.
To run the application from the command line you can do one of two things –
1. Go to the directory where the csproj file is located and type:
dotnet run
2. Go to the bin\debug\netcoreapp2.0 directory and type:
dotnet CoreWithKestrelFromConfig.dll
You can set Kestrel to listen on multiple urls, the format is this –
{ "urls": "http://localhost:62000/;http://localhost:62002/" }
Full source code available CoreWithKestrelFromConfighere.