Search code examples
c#asp.net-core.net-corekestrel-http-server

Configurable port number when using Kestrel?


I have done the following but it still doesn't work. Running dotnet myapp.dll still shows it's listening http://localhost:5000.

  1. Create hosting.json

Code:

{
  "server.url": "http://*:5001"
}
  1. Updated Program.cs

Code:

public class Program
{
    public static void Main(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("hosting.json", optional: true, reloadOnChange: true)
            .Build();

        var host = new WebHostBuilder()
            .UseConfiguration(config) // added
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            //.UseUrls("http://*:5001")
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}
  1. Updated project.json

Code:

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config",
      "NLog.config",
      "hosting.json"
    ]

Solution

    1. You need to change order: .SetBasePath should be called before file reading

      var config = new ConfigurationBuilder()
          .SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile("hosting.json", optional: true, reloadOnChange: true)
          .Build();
      
    2. Use server.urls, not server.url