Setting the Kestrel Port from appsettings.json

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 -

1{
2  "urls": "http://localhost:62000/"
3}

I also removed applicationUrl setting from the launchSettings.json file, now Visual Studio and the command line will set the application to the same port.

 1public class Program
 2{
 3    public static IConfiguration Configuration { get; set; }
 4    public static void Main(string[] args)
 5    {
 6        var builder = new ConfigurationBuilder();
 7        Configuration = builder.Build();
 8
 9        BuildWebHost(args).Run();
10    }
11
12    public static IWebHost BuildWebHost(string[] args) =>
13        WebHost.CreateDefaultBuilder(args)
14            .UseStartup<Startup>()
15            .UseConfiguration(Configuration)
16            .Build();
17}

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 -

1{
2   "urls": "http://localhost:62000/;http://localhost:62002/"
3}

Full source code available CoreWithKestrelFromConfighere.

comments powered by Disqus

Related